Skip to main content
 首页 » 编程设计

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

2025年05月04日15lovecherry

我想将我的数据框转换为一个字典,其中的键是一个 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']}