将两列Pandas数据框转换为以第一列为键的列表字典

3

我有以下数据框:

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

我想要做的是将它们转换成列表字典:
{ '1': ['foo','cux'],
  '2': ['qux','bar'],
  '3': ['fii']}

我该怎么做呢?

2个回答

8
你可以使用 groupbyapply 方法将数据进行分组,再使用 tolist 方法将结果转换为列表,最后使用 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']}

1
dct = {x:df.Genes[df.ClusterID == x].tolist() for x in set(df.ClusterID)}
# dct == {1: ['foo','cux'], 2: ['qux','bar'], 3: ['fii']}

作为你的ClusterID列由整数值组成,那么你的字典键也是整数。如果你想要像示例中一样使用字符串作为键,只需使用str函数即可。
dct = {str(x):df.Genes[df.ClusterID == x].tolist() for x in set(df.ClusterID)}

这里我们使用了一个字典推导式。表达式set(df.ClusterID)将为我们获取该列中唯一值的集合(我们可以使用集合,因为字典键是无序的)。df.Genes[df.ClusterID == x]将为我们获取与x相等的ClusterID值对应的Genes列中的值。使用tolist()将把pandas.Series返回到那里转换为列表。
因此,该字典表达式循环遍历ClusterID列中的每个唯一值,并将对应于该值的Genes值列表存储为字典中的一个列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接