gpt4 book ai didi

python - pandas 将 dataframe id 列转换为字典并将相应的列列出

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:51 25 4
gpt4 key购买 nike

我想将我的数据框转换为一个字典,其中的键是一个 id 列。我想将具有相应 id 的所有相应的第二列值放入列表中。

示例数据:

s1 = pd.Series(['A','A','B'],name = 's1')
s2 = pd.Series(['1','2','2'],name = 's2')

df = pd.concat([s1,s2],axis = 1)

s1 s2
A 1
A 2
B 2

我想要的输出

我如何获得带有映射的字典:

d = {'A':[1,2],'B':[2]}

最佳答案

还有两个选项

df.groupby('s1').s2.apply(list).to_dict()
Out[44]: {'A': ['1', '2'], 'B': ['2']}

s=df.groupby('s1').s2.apply(list)
dict(zip(s.index,s))
Out[48]: {'A': ['1', '2'], 'B': ['2']}

关于python - pandas 将 dataframe id 列转换为字典并将相应的列列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com