【问题标题】:How can I take a dataframe and split it into individual lists by column?如何获取数据框并按列将其拆分为单独的列表?
【发布时间】:2017-10-17 14:42:49
【问题描述】:

正如问题所说,我有一个很大但看起来像这样的数据框:

        ID    Count    ValueX    Value 2    Value 3
RowX    1      234.     255.       yes.      yes
RowY    1      123.     135.       543.      342
RowW    1      234.     235.       yes.      yes
RowJ    1      123.     115.       543.      342
RowA    1      234.     285.       yes.      yes
RowR    1      123.     165.       543.      342
RowX    2      234.     255.       yes.      yes
RowY    2      123.     135.       543.      342
RowW    2      234.     235.       yes.      yes
RowJ    2      123.     115.       543.      342
RowA    2      234.     285.       yes.      yes
RowR    2      123.     165.       543.      342
.
.
.
RowX    1233   234.     255.       yes.      yes
RowY    1233   123.     135.       543.      342
RowW    1233   234.     235.       yes.      yes
RowJ    1233   123.     115.       543.      342
RowA    1233   234.     285.       yes.      yes
RowR    1233   123.     165.       543.      342

我想要的是能够获取 df 并按列将其拆分为列表,以便我最终得到 IDCountValueXValue 2 和其余部分的列表.目前,我正在这样做:

IDlist = df_original.ID.tolist()
Countlist = df_original.Count.tolist()
...

这为我提供了我需要的解决方案,但我想知道是否有更短的方法将 df 拆分为列表。

【问题讨论】:

    标签: python-2.7 pandas anaconda


    【解决方案1】:

    您可以创建嵌套列表:

    L = df.values.T.tolist()
    
    print (L)
    [[1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
     [234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0],
     [255.0, 135.0, 235.0, 115.0, 285.0, 165.0, 255.0, 135.0, 235.0, 115.0, 285.0, 165.0], 
     ['yes.', '543.', 'yes.', '543.', 'yes.', '543.','yes.','543.','yes.','543.','yes.','543.'],
     ['yes', '342', 'yes', '342', 'yes', '342', 'yes', '342', 'yes', '342', 'yes', '342']]
    

    您可以按以下位置访问:

    print (L[0])
    [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
    

    或者更好的创建lists的字典:

    d = df.to_dict('l')
    print (d)
    {
    'Count':[234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0, 234.0, 123.0],
    'Value 3':['yes', '342', 'yes', '342', 'yes', '342','yes','342', 'yes', '342', 'yes', '342'],
    'ID': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], 
    'Value 2': ['yes.', '543.', 'yes.', '543.', 'yes.', '543.', 
                'yes.', '543.', 'yes.', '543.', 'yes.', '543.'], 
    'ValueX':[255.0, 135.0, 235.0, 115.0, 285.0, 165.0, 255.0, 135.0, 235.0, 115.0, 285.0,165.0]
    }
    

    您可以按列名访问,例如:

    print (d['ID'])
    [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多