如何将列表转换为 pandas 数据框
how to convert a list into a pandas dataframe
我有以下代码:
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 个条目。
当我将其转换为 pandas 数据框时,我将数据框中的条目作为列表获取。 :
pd.DataFrame(rows, columns=["State", "R", "D", "incumbent"])
但我想要这样的数据框
新的信息变量看起来像这样
既然你介意列中的对象是列表,我会使用生成器来删除包裹你的项目的列表:
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"])
您可以使用一些内置的 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
我有以下代码:
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 个条目。
当我将其转换为 pandas 数据框时,我将数据框中的条目作为列表获取。 :
pd.DataFrame(rows, columns=["State", "R", "D", "incumbent"])
但我想要这样的数据框
新的信息变量看起来像这样
既然你介意列中的对象是列表,我会使用生成器来删除包裹你的项目的列表:
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"])
您可以使用一些内置的 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