将两列Pandas数据帧转换为列表的字典,第一列为键 [英] Convert two columns Pandas data frame to dictionary of list with first column as keys
本文介绍了将两列Pandas数据帧转换为列表的字典,第一列为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
import pandas as pd
df = pd.DataFrame({
"ClusterID" : [1,2,2,1,3],
"Genes" : ['foo','qux','bar','cux','fii'],
})
其中看起来像这样:
ClusterID Genes
0 1 foo
1 2 qux
2 2 bar
3 1 cux
4 3 fii
我想做的是将它们转换成列表的字典: p>
What I want to do is to convert them into a dictionary of list:
{ '1': ['foo','cux'],
'2': ['qux','bar'],
'3': ['fii']}
我这样做?
推荐答案
你可以使用 groupby
和 apply
tolist
,然后使用 Series.to_dict
:
You can use groupby
and apply
tolist
and then use Series.to_dict
:
import pandas as pd
df = pd.DataFrame({
"ClusterID" : [1,2,2,1,3],
"Genes" : ['foo','qux','bar','cux','fii'],
})
print df
ClusterID Genes
0 1 foo
1 2 qux
2 2 bar
3 1 cux
4 3 fii
s = df.groupby('ClusterID')['Genes'].apply(lambda x: x.tolist())
print s
ClusterID
1 [foo, cux]
2 [qux, bar]
3 [fii]
Name: Genes, dtype: object
print s.to_dict()
{1: ['foo', 'cux'], 2: ['qux', 'bar'], 3: ['fii']}
这篇关于将两列Pandas数据帧转换为列表的字典,第一列为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文