循环访问分组数据框中的组 [英] Looping over groups in a grouped dataframe
本文介绍了循环访问分组数据框中的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个小例子:
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"])
我要与frame
分组
grouped=frame.groupby(frame.index)
然后我要通过以下方式遍历组:
Then I want to loop over the groups by:
for group in grouped:
但是我坚持下一步:如何在每个循环中将group
提取为pandas DataFrame,以便我可以对其进行进一步处理?
But I'm stuck on the next step: How can I extract the group
in each loop as a pandas DataFrame so I can further process it?
推荐答案
df.groupby
返回2元组的列表:索引和组.您可以像这样遍历每个组:
df.groupby
returns a list of 2-tuples: the index, and the group. You can iterate over each group like this:
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.
这篇关于循环访问分组数据框中的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文