python - 将类型为 'object' 的数据帧列转换为类型列表

标签 python pandas dataframe

尝试将 dataframeobject 类型列转换为实际需要的 dicts 列表。

print df['A'].dtype
object

print df['A'][:1]
[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]

是否可以将 df['A'] 作为 dicts 的列表检索为 dicts?非常感谢任何帮助。

最佳答案

使用json

import json

df.A.apply(json.loads)

0    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
1    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
2    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
3    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
4    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
5    [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
Name: A, dtype: object

设置

df = pd.DataFrame([
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
        '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]',
    ],
    columns=['A'])

关于python - 将类型为 'object' 的数据帧列转换为类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241590/

相关文章:

python-2.7 - 用python减去两列不同的Dataframe

python - 按行搜索和修改 CSV 文件,仅搜索一个或两个元素,不一定是该行中的所有元素

python - Plotly:如何使用散点图显示 multiIndex 数据框?

python - 如何在 Flask 服务器中将 python JSON 转换为 html 表?

python - Pandas:按日期对一列进行分组并计算另一列中特定值的累计数

python - 如何在数据框中选择 n-1 列

python - 计算 pandas 数据框中多列中唯一值的出现次数

Python 数据类属性初始化后

python - 将列表转换为 Pandas 系列时出现 KeyError

python - 编写检查所有 pandas DataFrame 列值是否满足特定值?