简体   繁体   English

将'object'类型的dataframe列转换为类型列表

[英]convert dataframe column of type 'object' into type list

Trying to convert the object type column of a dataframe into a list of dicts as it actually needs to be. 尝试将dataframeobject类型列转换为实际需要的dicts列表。

print df['A'].dtype
object

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

Is it possible to retrieve df['A'] as a list of dicts as dicts ? 是否有可能恢复df['A']作为列表dicts作为dicts Any help highly appreciated. 任何帮助高度赞赏。

use json 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

Setup 建立

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM