使用groupby()、value_counts()和join从数据框中获取最大值并连接文本
我想把日期分组,然后统计每天相同项目的数量,接着找出数量的最大值,并把这些项目合并在一起。我的数据框是这样的。
df= pd.DataFrame({'date': ['2020-09-10','2020-09-10','2020-09-10','2020-09-10','2020-09-08','2020-09-08'],
'fruit':['apple','banana','apple','oragne','apple','orange'],
'value':['1','1','2','3','3','3']})
input:
x = df.groupby('date')['value'].value_counts().rename('count').reset_index().drop_duplicates('date')
output:
date value count
0 2020-09-08 3 2
1 2020-09-10 1 2
input :
df.groupby(['date', 'value'])['fruit'].apply(' '.join)
output:
date value
2020-09-08 3 apple orange
2020-09-10 1 apple banana
2 apple
3 oragne
我期望的输出结果是:
output:
date value count fruit
0 2020-09-08 3 2 apple orange
1 2020-09-10 1 2 apple banana
1 个回答
2
如果我理解正确的话,你想要找出那些在同一天或同一个值上,项目数量最多的行。
你可以使用一个自定义的 groupby.agg
方法来实现:
out = (
df.groupby(['date', 'value'], as_index=False)['fruit']
.agg(**{'count': 'count', 'fruit': ' '.join})
.loc[lambda d: d.groupby('date')['count'].idxmax()]
)
或者,如果你想要在每个日期上保留所有的最大计数,而不仅仅是一个:
out = (
df.groupby(['date', 'value'], as_index=False)['fruit']
.agg(**{'count': 'count', 'fruit': ' '.join})
.loc[lambda d: d.groupby('date')['count'].transform('max').eq(d['count'])]
)
或者你可以在你现有的代码基础上,使用 merge
方法:
# simplification of the way to compute "x"
# you could also use your original code
x = df[['date', 'value']].value_counts().reset_index().drop_duplicates('date')
out = x.merge(df.groupby(['date', 'value'], as_index=False)
['fruit'].agg(' '.join), how='left')
注意:像我第一段代码那样,这种方法只会保留第一个最大计数,即使每个日期上有多个最大值。
输出结果:
date value count fruit
0 2020-09-08 3 2 apple orange
1 2020-09-10 1 2 apple banana