正在查找在多个列中具有最大值的组的行:
pd.DataFrame([{‘grouper’: ‘a’, ‘col1’: 1, ‘col2’: 3, ‘uniq_id’: 1}, {‘grouper’: ‘a’, ‘col1’: 2, ‘col2’: 4, ‘uniq_id’: 2}, {‘grouper’: ‘a’, ‘col1’: 3, ‘col2’: 2, ‘uniq_id’: 3}])
col1 col2 grouper uniq_id
0 1 3 a 1
1 2 4 a 2
2 3 2 a 3
在上面,我按“grouper”列进行分组。在“a”组中,我希望得到最大值为col1和col2的行,在这种情况下,当我对数据帧进行分组时,我希望获得uniq_id的行,因为它的col1/col2值最高,为4,因此结果是:
^{pr2}$
在我的实际例子中,我使用的是时间戳,所以我实际上并不期望打领带。但是在平局的情况下,我不关心我在组中选择哪一行,因此在这种情况下,它将是组的first。在
3条回答
网友
1楼 ·
有趣的方法。添加另一个方法只是为了展示apply(我非常喜欢)的强大功能,并使用前面提到的一些其他方法。在
import pandas as pd
df = pd.DataFrame(
[
{"grouper": "a", "col1": 1, "col2": 3, "uniq_id": 1},
{"grouper": "a", "col1": 2, "col2": 4, "uniq_id": 2},
{"grouper": "a", "col1": 3, "col2": 2, "uniq_id": 3},
]
)
def find_max(grp):
# find max value per row, then find index of row with max val
max_row_idx = grp[["col1", "col2"]].max(axis=1).idxmax()
return grp.loc[max_row_idx]
df.groupby("grouper").apply(find_max)
IIUC使用transform,然后与原始数据帧进行比较
g=df.groupby('grouper')
s1=g.col1.transform('max')
s2=g.col2.transform('max')
s=pd.concat([s1,s2],axis=1).max(1)
df.loc[df[['col1','col2']].eq(s,0).any(1)]
Out[89]:
col1 col2 grouper uniq_id
1 2 4 a 2
还有一种方法可以尝试:
# find row wise max value
df['row_max'] = df[['col1','col2']].max(axis=1)
# filter rows from groups
df.loc[df.groupby('grouper')['row_max'].idxmax()]
col1 col2 grouper uniq_id row_max
1 2 4 a 2 4
稍后可以使用df.drop(‘row_max’, axis=1)删除{}
我用来使用的功能如下:
我要获取一行的数据出来:
import pandas as pd
df = pd.read_excel('新建 XLSX 工作表.xlsx', 0,
usecols=['物料名称', '物料型号', '数量', '单位', '入库时间', '供应商名称', '入库编号', '单价(不含税)'])
# print(df.head())
def find_max(grp):
# find max value per row, then find index of row with max val
max_row_idx = grp['单价(不含税)'].idxmax()
return grp.loc[max_row_idx]
def find_min(grp):
# find min value per row, then find index of row with min val
min_row_idx = grp['单价(不含税)'].idxmin()
return grp.loc[min_row_idx]
if __name__ == '__main__':
df_max = df.groupby(by=['物料型号']).apply(find_max)
df_min = df.groupby(by=['物料型号']).apply(find_min)
df_min['分割一下'] = ' ||| '
df_max['入库编号'] = df_max['入库编号'].astype('string')
df_min['入库编号'] = df_min['入库编号'].astype('string')
# 改列名
df_min.rename(columns={'单价(不含税)': '(低价)单价(不含税)'}, inplace=True)
df_max.rename(columns={'单价(不含税)': '(高价)单价(不含税)'}, inplace=True)
df = pd.concat([df_min, df_max], axis=1)
df['差价'] = df['(高价)单价(不含税)'] - df['(低价)单价(不含税)']
df.to_excel('a.xlsx', index=False)