我想在这个数据框列中聚合。
data = {'one':['one', 'five', 'one', 'one'],
'two':['one', 'five', 'one', 'one']}
df = pd.DataFrame(data)
df
使用以下代码:
new_df = df.groupby('one').agg(names = ('two', 'sum'))
输出将是:
five five
one oneoneone
如何在汇总结果之间添加逗号?
想要的结果:
five five
one one, one, one
更新
我需要在两个不同的数据帧之间进行聚合。让我们说:
# First DataFrame
id country_name
1 america
5 uk
# Second DataFrame
id state_name
1 california, boston, texas
5 london
想要的结果:取决于id
我如何添加state_name
到新的数据框?
# Creating a new column, so the updated first dataframe will be like this:
id country_name state_name
1 america california, boston, texas
5 uk london
您只需要添加','.join
而不是sum
.
new_df = df.groupby('one').agg(names = ('two', ', '.join))
输出:
names
one
five five
one one, one, one
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句