Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

python - How to reset a DataFrame's indexes for all groups in one step?

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...