【问题标题】:Groupby to Dataframe in PandasGroupby 到 Pandas 中的数据框
【发布时间】:2018-01-29 10:36:37
【问题描述】:

基本上,我使用一个包含数千个数据的 excel 文件,并且我正在使用 pandas 来读取文件。

import pandas as pd
agg = pd.read_csv('Station.csv', sep = ',')

然后我所做的就是根据这些类别对数据进行分组,

month_station = agg.groupby(['month','StationName'])

groupby 不会用于计算平均值、中位数等,而只是根据月份和站名聚合数据。 这就是问题想要的

现在,我想将 month_station 输出到一个 excel 文件中,所以首先我需要将 groupby 传输到数据框中。

我看过例子:

pd.DataFrame(month_station.size().reset_index(name = "Group_Count"))

但问题是,我不需要数据的大小/计数,而只是根据月份和站名对其进行分组,不需要计数或排序。我尝试删除 size(),但它给了我一个错误。

我只是希望将 month_station 的内容移植到数据帧中,这样我就可以继续操作并将其输出为 csv 文件,但这似乎很复杂。

【问题讨论】:

  • set_index("your_index_name") 怎么样?
  • @RHSmith159 它会在哪里? pd.DataFrame(month_station.set_index("name"))?
  • 我不是 100% 确定,但我认为它只是 new_df = month_station.set_index("name")
  • @RHSmith159 它会产生错误“无法访问'DataFrameGroupBy'对象的可调用属性'set_index',请尝试使用'apply'方法”
  • 抱歉,如果没有一些输入和预期输出,就无法理解您想要什么。

标签: python pandas dataframe group-by


【解决方案1】:

groupby 的本质是让您可以得出聚合计算,例如平均值或计数或总和等。如果您只是想查看每一对月份和站名,请尝试以下操作:

month_station = agg.groupby(['month','StationName'],as_index=False).count()
month_station = month_station['month','StationName']

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2022-01-18
    • 2018-04-06
    相关资源
    最近更新 更多