pandas :分组:如何一步重置所有组的索引? [英] pandas: group by: how to reset indexes for all groups in one step?
问题描述
我尝试将我的数据框分组到组中
df = pd.DataFrame({'A':['' foo','bar','foo','bar',
'foo','bar','foo','foo'],
'B':['1',' 2','3','4',
'5','6','7','8'],
})
分组= df。 groupby('A')
我得到2个小组
AB
0 foo 1
2 foo 3
4 foo 5
6 foo 7
7 foo 8
AB
1 bar 2
3 bar 4
5 bar 6
现在我想为每个组分别重置索引
print grouped.get_group('foo' ).reset_index()
print grouped.get_group('bar').setup_index()
最后我得到结果
AB
0 foo 1
1 foo 3
2 foo 5
3 foo 7
4 foo 8
AB
0 bar 2
1 bar 4
2 bar 6
有没有更好的方法来做到这一点? (例如:自动为每个组调用一些方法)
传入 as_index = False
reset_index
来再次创建groupby-d列的列: 在[11]中:grouped = df.groupby('A',as_index = False)
在[12]中:grouped.get_group 'foo')
出[12]:
AB
0 foo 1
2 foo 3
4 foo 5
6 foo 7
7 foo 8
注意:正如上面的例子中指出的那样,上面的索引是不是 [0,1,2,...]
,我声称这在实践中永远不会起作用 - 如果你打算只能通过一些奇怪的箍筋 - 它会变得更加冗长,不太可读,效率也不高......
I've tried to split my dataframe to groups
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['1', '2', '3', '4',
'5', '6', '7', '8'],
})
grouped = df.groupby('A')
I get 2 groups
A B
0 foo 1
2 foo 3
4 foo 5
6 foo 7
7 foo 8
A B
1 bar 2
3 bar 4
5 bar 6
Now I want to reset indexes for each group separately
print grouped.get_group('foo').reset_index()
print grouped.get_group('bar').reset_index()
Finally I get the result
A B
0 foo 1
1 foo 3
2 foo 5
3 foo 7
4 foo 8
A B
0 bar 2
1 bar 4
2 bar 6
Is there better way how to do this? (For example: automatically call some method for each group)
Pass in as_index=False
to the groupby, then you don't need to reset_index
to make the groupby-d columns columns again:
In [11]: grouped = df.groupby('A', as_index=False)
In [12]: grouped.get_group('foo')
Out[12]:
A B
0 foo 1
2 foo 3
4 foo 5
6 foo 7
7 foo 8
Note: As pointed out (and seen in the above example) the index above is not [0, 1, 2, ...]
, I claim that this will never matter in practice - if it does you're going to have to just through some strange hoops - it's going to be more verbose, less readable and less efficient...
这篇关于 pandas :分组:如何一步重置所有组的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!