Created
June 9, 2018 10:40
-
-
Save okdolly-001/b0bb7505b346fffc06a663dda1cdfca8 to your computer and use it in GitHub Desktop.
Groupby #pandas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
df = pd.DataFrame( | |
{ | |
'AAA': [1,1,1,2,2,2,2,3,3], | |
'BBB': [2,1,3,4,5,1,2,3,7] | |
} | |
) | |
print(df,'\n') | |
#First group df by the classes in A (1,2,3),then get the index of the minimum number of B in each class of A. | |
group_min = df.loc[df.groupby('AAA')['BBB'].idxmin()] | |
print(group_min, '\n') | |
#sort then take first of each | |
First_of_each = df.sort_values(by='BBB').groupby('AAA', as_index=False).first() | |
print(First_of_each) | |
-------------------------------------------------------------------------------------------------- | |
Output: | |
AAA BBB | |
0 1 2 | |
1 1 1 | |
2 1 3 | |
3 2 4 | |
4 2 5 | |
5 2 1 | |
6 2 2 | |
7 3 3 | |
8 3 7 | |
AAA BBB | |
1 1 1 | |
5 2 1 | |
7 3 3 | |
AAA BBB | |
0 1 1 | |
1 2 1 | |
2 3 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment