我有个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只有在条件为100时,我才想对键列Key1和Key2 执行groupby,并找到分数的最大值。
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发布于 2020-12-14 05:20:37
这应该能行
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 4000https://stackoverflow.com/questions/65283465
复制相似问题