因此,所有内容都应按第 0 列聚合,并且当第 1 列中的字符串具有相同名称时,应添加第 1 列中的所有字符串,并对第 2 列中的数字求和。
使用以下代码,我可以聚合字符串,但无需对数字求和:
df2= df1.groupby([0]).agg(lambda x: ','.join(set(x))).reset_index()
df2
最佳答案
避免任意数量的列
您想要的输出表明您有任意数量的列,具体取决于每个组 0
的 1
中的值的数量。这是反 Pandas 的,它强烈针对任意数量的行。因此按系列操作是首选。
所以你可以使用groupby
+ sum
来存储你需要的所有信息。
df = pd.DataFrame({0: ['2008-04_E.pdf']*3,
1: ['Mat1', 'Mat2', 'Mat2'],
2: [3, 1, 1]})
df_sum = df.groupby([0, 1]).sum().reset_index()
print(df_sum)
0 1 2 0 2008-04_E.pdf Mat1 3 1 2008-04_E.pdf Mat2 2
But if you insist...
If you insist on your unusual requirement, you can achieve it as follows via df_sum
calculated as above.
key = df_sum.groupby(0)[1].cumcount().add(1).map('Key{}'.format)
res = df_sum.set_index([0, key]).unstack().reset_index().drop('key', axis=1)
res.columns = res.columns.droplevel(0)
print(res)
Key1 Key2 Key1 Key2 0 2008-04_E.pdf Mat1 Mat2 3 2
关于Python df groupby 与 agg 用于字符串和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53410407/