【问题标题】:Convert two columns Pandas data frame to dictionary of list with first column as keys将两列 Pandas 数据框转换为以第一列为键的列表字典
【发布时间】:2016-05-03 22:53:56
【问题描述】:

我有以下数据框:

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']}

我该怎么做?

【问题讨论】:

    标签: python dictionary pandas


    【解决方案1】:

    您可以使用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']}
    

    【讨论】:

      【解决方案2】:
      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] 将为我们获取 Genes 列中与 ClusterID 值等于 x 的行相对应的值。使用 tolist() 会将返回的 pandas.Series 转换为列表。

      因此,此字典表达式循环遍历 ClusterID 列中的每个唯一值,并将与该值对应的 Genes 值列表存储为该值下的字典中的列表键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-12
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 2016-10-23
        • 2019-07-27
        • 2017-06-22
        • 1970-01-01
        相关资源
        最近更新 更多