将列表内的键值对添加到pandas数据框列

时间:2018-07-07 21:47:49

标签: python python-3.x list pandas dictionary

我的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

1 个答案:

答案 0 :(得分:1)

事情是...你得到了一系列。改为这样做:

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...