我有一个 Pandas DataFrame,DF:
我想以以下形式将其放入字典中:
{ "Apple red" : ['Texas', 'California'], "Banana yellow" : ['Indiana', 'Florida'] }
其中 Key = A 列和 B 列(和)中的字符串串联
值 = 列表中 C 列(基于 groupby)的所有对应字符串。
我不知道如何实现这一目标。
重要说明:如果字典的键要分组的列超过 3 列,它也应该有效
最佳答案
尝试:
x = dict(
df.groupby(df["Column A"] + " " + df["Column B"])["Column C"].agg(list)
)
print(x)
打印:
{'Apple red': ['Texas', 'California'], 'Banana yellow': ['Indiana', 'Florida']}
关于python - 根据 pandas DataFrame 中的组将字符串组合到列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74200986/