我有以下代码:
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))
Run Code Online (Sandbox Code Playgroud)
现在我想将我的行列表转换为pandas数据框.我的行列表的结构如下所示,我的列表有32个条目.

当我将其转换为pandas数据帧时,我将数据帧中的条目作为列表获取.:
pd.DataFrame(rows, columns=["State", "R", "D", "incumbent"])
Run Code Online (Sandbox Code Playgroud)

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

新的info变量看起来像这样

既然您想要列中的对象是列表,我会使用生成器来删除包装项目的列表:
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)
Run Code Online (Sandbox Code Playgroud)
生成器与此函数的工作方式类似,但不是在内存中不必要地将列表作为中间步骤实现,而是将列表中的每一行传递给行列表的使用者:
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
Run Code Online (Sandbox Code Playgroud)
然后组合你的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
Run Code Online (Sandbox Code Playgroud)
或者您可以使用列表推导或生成器表达式(显示)来执行基本相同的操作:
>>> 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"])
Run Code Online (Sandbox Code Playgroud)
您可以使用一些内置的python列表操作,并执行以下操作:
df['col1'] = df['col1'].apply(lambda i: ''.join(i))
Run Code Online (Sandbox Code Playgroud)
这将产生:
col1 col2
0 a [d]
1 b [e]
2 c [f]
Run Code Online (Sandbox Code Playgroud)
显然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})
Run Code Online (Sandbox Code Playgroud)
然后你可以循环列
for col in df.columns:
df[col] = df[col].apply(lambda i: ''.join(i))
Run Code Online (Sandbox Code Playgroud)
它转换一个像下面这样的数据框:
col1 col2 col3
0 [a] [e] [i]
1 [b] [f] [j]
2 [c] [g] [k]
3 [d] [h] [l]
Run Code Online (Sandbox Code Playgroud)
并成为
col1 col2 col3
0 a e i
1 b f j
2 c g k
3 d h l
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88690 次 |
| 最近记录: |