如何将列表转换为pandas数据帧

时间:2015-01-30 01:06:09

标签: python pandas

我有以下代码:

rows =[]
for dt in new_info:
    x =  dt['state']
    est = dt['estimates']

    col_R = [val['choice'] for val in est if val['party'] == 'Rep']
    col_D = [val['choice'] for val in est if val['party'] == 'Dem']

    incumb = [val['party'] for val in est if val['incumbent'] == True ]

    rows.append((x, col_R, col_D, incumb))

现在我想将我的行列表转换为pandas数据框。我的行列表的结构如下所示,我的列表有32个条目。

enter image description here

当我将其转换为pandas数据框时,我将数据框中的条目作为列表获取。 :

pd.DataFrame(rows, columns=["State", "R", "D", "incumbent"])  

enter image description here

但我希望我的数据框像这样

enter image description here

新的info变量如下所示 enter image description here

2 个答案:

答案 0 :(得分:9)

由于您认为列中的对象是列表,我会使用生成器来删除包装项目的列表:

import pandas as pd
import numpy as np
rows = [(u'KY', [u'McConnell'], [u'Grimes'], [u'Rep']),
        (u'AR', [u'Cotton'], [u'Pryor'], [u'Dem']),
        (u'MI', [u'Land'], [u'Peters'], [])]

def get(r, nth):
    '''helper function to retrieve item from nth list in row r'''
    return r[nth][0] if r[nth] else np.nan

def remove_list_items(list_of_records):
    for r in list_of_records:
        yield r[0], get(r, 1), get(r, 2), get(r, 3)

生成器与此函数的工作方式类似,但不是在内存中不必要地将列表实现为中间步骤,而是将列表中的每一行传递给行列表的使用者:

def remove_list_items(list_of_records):
    result = []
    for r in list_of_records:
        result.append((r[0], get(r, 1), get(r, 2), get(r, 3)))
    return result

然后组合你的DataFrame将数据传递给生成器(或者如果你愿意的话,还是列表版本。)

>>> df = pd.DataFrame.from_records(
        remove_list_items(rows), 
        columns=["State", "R", "D", "incumbent"])
>>> df
  State          R       D incumbent
0    KY  McConnell  Grimes       Rep
1    AR     Cotton   Pryor       Dem
2    MI       Land  Peters       NaN

或者您可以使用列表推导或生成器表达式(如图所示)来执行基本相同的操作:

>>> df = pd.DataFrame.from_records(
      ((r[0], get(r, 1), get(r, 2), get(r, 3)) for r in rows), 
      columns=["State", "R", "D", "incumbent"])

答案 1 :(得分:7)

您可以使用一些内置的python列表操作,并执行以下操作:

df['col1'] = df['col1'].apply(lambda i: ''.join(i))

将产生:

    col1 col2
0    a  [d]
1    b  [e]
2    c  [f]

显然,col2未进行格式化以显示对比度。

修改

根据OP的要求,如果您要对所有列实施apply(lambda...),那么您可以使用与上面的每行替换'col1'的行显式设置每一列。您希望更改的列名称,或者您可以像这样循环遍历列:

如果您的数据框类型为

x = [['a'],['b'],['c'],['d']]
y = [['e'],['f'],['g'],['h']]
z = [['i'],['j'],['k'],['l']]

df = pd.DataFrame({'col1':x, 'col2':y, 'col3':z})

然后你可以遍历列

for col in df.columns:
    df[col] = df[col].apply(lambda i: ''.join(i))

转换一个以:

开头的数据框
   col1 col2 col3
0  [a]  [e]  [i]
1  [b]  [f]  [j]
2  [c]  [g]  [k]
3  [d]  [h]  [l]

并成为

    col1 col2 col3
0    a    e    i
1    b    f    j
2    c    g    k
3    d    h    l