迭代数据框中的组

Iterating over groups in a dataframe

我遇到的问题是我想对数据框进行分组,然后在分组后使用函数来操作数据。例如,我想按日期对数据进行分组,然后遍历日期组中的每一行以解析为函数?

问题是 groupby 似乎创建了一个键元组,然后创建了一个由数据中所有行组成的巨大字符串,使得无法遍历每一行

当您在数据框上应用 groupby 时,您得到的不是行,而是数据框组。例如,考虑:

df
    ID        Date  Days  Volume/Day
0  111  2016-01-01    20          50
1  111  2016-02-01    25          40
2  111  2016-03-01    31          35
3  111  2016-04-01    30          30
4  111  2016-05-01    31          25
5  112  2016-01-01    31          55
6  112  2016-01-02    26          45
7  112  2016-01-03    31          40
8  112  2016-01-04    30          35
9  112  2016-01-05    31          30

for i, g in df.groupby('ID'):
     print(g, '\n')


    ID        Date  Days  Volume/Day
0  111  2016-01-01    20          50
1  111  2016-02-01    25          40
2  111  2016-03-01    31          35
3  111  2016-04-01    30          30
4  111  2016-05-01    31          25 

    ID        Date  Days  Volume/Day
5  112  2016-01-01    31          55
6  112  2016-01-02    26          45
7  112  2016-01-03    31          40
8  112  2016-01-04    30          35
9  112  2016-01-05    31          30 

对于您的情况,如果您想生成汇总结果,您可能应该查看 dfGroupby.apply, if you want to apply some function on your groups, dfGroupby.transform to produce like indexed dataframe (see docs for explanation) or dfGroupby.agg

你会这样做:

r = df.groupby('Date').apply(your_function) 

您将函数定义为:

def your_function(df):
    ... # operation on df
    return result

如果您在实施过程中遇到问题,请提出一个新问题,post 您的数据和代码,以及任何相关的 errors/tracebacks。编码愉快。