pandas 循环分组数据框中的组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45797633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:17:13  来源:igfitidea点击:

Looping over groups in a grouped dataframe

pythonpandasdataframepandas-groupby

提问by Rockbar

Consider this small example:

考虑这个小例子:

data={"X":[1, 2, 3, 4, 5], "Y":[6, 7, 8, 9, 10], "Z": [11, 12, 13, 14, 15])
frame=pd.DataFrame(data,columns=["X","Y","Z"],index=["A","A","A","B","B"])

I want to group framewith

我想frame

grouped=frame.groupby(frame.index)

Then I want to loop over the groups by:

然后我想通过以下方式遍历组:

for group in grouped:

But I'm stuck on the next step: How can I extract the groupin each loop as a pandas DataFrame so I can further process it?

但我坚持下一步:如何将group每个循环中的数据提取为Pandas数据帧,以便我可以进一步处理它?

采纳答案by cs95

df.groupbyreturns a list of 2-tuples: the index, and the group. You can iterate over each group like this:

df.groupby返回一个 2 元组列表:索引和组。您可以像这样迭代每个组:

for _, g in frame.groupby(frame.index):
    .... # do something with `g`

However, if you want to perform some operation on the groups, there are probably better ways than iteration.

但是,如果要对组执行某些操作,可能有比迭代更好的方法。

回答by Scott Boston

Here is an example:

下面是一个例子:

groups = frame.groupby(level=0)

for n,g in groups:
    print('This is group '+ str(n)+'.')
    print(g)
    print('\n')

Output:

输出:

This is group A.
   X  Y   Z
A  1  6  11
A  2  7  12
A  3  8  13


This is group B.
   X   Y   Z
B  4   9  14
B  5  10  15