我有一个 df
Key1 Key2 Condition Score
K11 K21 100 1000
K11 K21 200 3000
K11 K21 100 2000
K12 K22 100 12
K12 K22 200 133
K12 K22 100 300
K14 K24 100 144
K14 K24 200 122
K14 K24 100 4000
我想对键列进行分组,Key1
并且Key2
仅当条件为 100并找到 Score 的最大值时。
df_trial=(df['Condition']=='100').groupby(['Key1','Key2'], as_index=False).max('Score')
此代码似乎不起作用并给出错误。我怎样才能达到所需的输出
预期输出
Key1 Key2 Condition max_Score
K11 K21 100 2000
K12 K22 100 300
K14 K24 100 4000
这应该工作
import numpy as np
import pandas as pd
df = pd.DataFrame({'Key1': ['K11', 'K11', 'K11', 'K12', 'K12', 'K12', 'K14', 'K14', 'K14'],
'Key2': ['K21', 'K21', 'K21', 'K22', 'K22', 'K22', 'K24', 'K24', 'K24'],
'Condition': [100, 200, 100, 100, 200, 100, 100, 200, 100],
'Score': [1000, 3000, 2000, 12, 133, 300, 144, 122, 4000]})
cond = df['Condition']==100
df_out = df.loc[cond].groupby(["Key1", "Key2"])['Score'].max().reset_index()
print(df_out)
Key1 Key2 Score
0 K11 K21 2000
1 K12 K22 300
2 K14 K24 4000
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句