尝试将 dataframe
的 object
类型列转换为实际需要的 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/