简体   繁体   中英

pandas get row with min column value per group

I want to get all rows with min column value per group,

example:

df = pd.DataFrame({'asset_symbol': ['100', '100', '100', '1015', '1015'],
 'percent_thresh': [0.75, 0.85, 0.95, 0.75, 0.85],
 'rank': [7.0, 7.0, 4.0, 2.0, 3.0]})

+--------------+----------------+------+
| asset_symbol | percent_thresh | rank |
+--------------+----------------+------+
| 100          | 0.75           | 7    |
+--------------+----------------+------+
| 100          | 0.85           | 7    |
+--------------+----------------+------+
| 100          | 0.95           | 4    |
+--------------+----------------+------+
| 1015         | 0.75           | 2    |
+--------------+----------------+------+
| 1015         | 0.85           | 3    |
+--------------+----------------+------+

desired table:

+--------------+----------------+------+
| asset_symbol | percent_thresh | rank |
+--------------+----------------+------+
| 100          | 0.95           | 4    |
+--------------+----------------+------+
| 1015         | 0.75           | 2    |
+--------------+----------------+------+

my attempt was:

def max_row(df, column):
    return df.loc[df[column].idxmin()]

df.groupby('asset_symbol').apply(max_row, 'rank')

however I generally refrain from using apply

IIUC,

df.loc[df.groupby('asset_symbol')['rank'].idxmin()]

Output:

asset_symbol  percent_thresh  rank
2          100            0.95   4.0
3         1015            0.75   2.0

Let us do sort_values + drop_duplicates

df.sort_values('rank').drop_duplicates('asset_symbol')
  asset_symbol  percent_thresh  rank
3         1015            0.75   2.0
2          100            0.95   4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM