Python 将列表中的键值对添加到dataframe列中
我把listA当作Python 将列表中的键值对添加到dataframe列中,python,python-3.x,list,pandas,dictionary,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', 'applica
[{'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
问题是。。。你有一个系列。改为这样做:
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...
@James在这种情况下,您将执行
df['newcolumn']=pd.Series(listA)
或简单地:df['newcolumn']=listA
。还是我遗漏了什么?你能看看这个https://stackoverflow.com/questions/51574485/match-keywords-in-pandas-column-with-another-list-of-elements
。我没有得到解决办法