gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:25:41 24 4
gpt4 key购买 nike

尝试将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com