首页 > 解决方案 > 将列表内的键值对添加到熊猫数据框列中

问题描述

我有 listA 作为

[{'index': 0,
  'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
 {'index': 1,
  'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']},
 {'index': 2,
  'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}]

`

我想将它作为第一个单元格的第一个元素添加到 pandas 列中。输出我预计为: -

Column_new
{'index': 0,'keywords': ['nuclear','china','force','capabilities','pentagon','defence']}
{'index': 1,'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']}
{'index': 2,'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}

我所做的是:-

df = pd.DataFrame(listA,col=['Column_new'])

但它给出了一个具有 NaN 值的数据框,

   Column_new
0  NaN

1  NaN

2  NaN

标签: pythonpython-3.xlistpandasdictionary

解决方案


问题是……你有一个系列。改为这样做:

df = pd.Series(listA).to_frame('Column_new')

完整示例:

import pandas as pd

listA = [{'index': 0,
  'keywords': ['nuclear','china','force','capabilities','pentagon','defence']},
 {'index': 1,
  'keywords': ['pakistan', 'membership', 'china', 'nsg', 'kirby', 'meets']},
 {'index': 2,
  'keywords': ['payment', 'rbi', 'applications', 'bill', 'bbpou', 'payments']}]


df = pd.Series(listA).to_frame('Column_new')
print(df)

回报:

                                          Column_new
0  {'index': 0, 'keywords': ['nuclear', 'china', ...
1  {'index': 1, 'keywords': ['pakistan', 'members...
2  {'index': 2, 'keywords': ['payment', 'rbi', 'a...

推荐阅读