python - 将列表内的键值对添加到熊猫数据框列中
问题描述
我有 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
解决方案
问题是……你有一个系列。改为这样做:
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...
推荐阅读
- c++ - 为什么数组上的 sizeof 运算符会给出不正确的结果?
- python - 如何使用 plotly、mapbox、python 创建方形网格?
- html - 获取第二个 div 的 span 中的元素属性值
- python - Python Ursina,我怎样才能得到球员的位置?
- r - 每个 id 不同的特定时间段的平均观察量
- flutter - Flutter TextButton 填充
- java - org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=text/html;charset=iso-8859-1,
- c# - 使用没有分离服务和存储库的 CQRS 真的会影响代码质量吗?
- c - 为什么我插入第一个元素后我的程序会终止?
- annotations - Squash Lombok 注释