简体   繁体   English

如何转换 pandas dataframe 将字符串数组转换为数组

[英]how to convert pandas dataframe convert string array to array

I am going to read a csv file and send to json stream format.我将阅读 csv 文件并发送到 json stream 格式。
One of the coulmn is in array format but in pandas dataframe it will return string format.其中之一是数组格式,但在 pandas dataframe 中它将返回字符串格式。
How cany I convert "attributes_changed" column from string array to normal array format?如何将“attributes_changed”列从字符串数组转换为普通数组格式?

Sample Code:示例代码:

import json
import pandas as pd

sample = {"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": "[\'metadataStatus\', \'elements\']"}
df = pd.DataFrame(data=sample, index=[0])

df_with_seq_id = [(json.dumps(rec), idx) for (idx, rec) in df.to_dict(orient='index').items()]

Current Result当前结果

[('{"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": "['metadataStatus', 'elements']" }', 0)] [('{"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": "['metadataStatus', 'elements']" }', 0)]

Expected Result (Removed double quotes)预期结果(删除双引号)

[('{"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": ['metadataStatus', 'elements'] }', 0)] [('{"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": ['metadataStatus', 'elements'] }', 0)]

You can simply apply eval on column attributes_changed to interpret the string values as an array:您可以简单地将eval应用于列attributes_changed以将字符串值解释为数组:

import json
import pandas as pd

sample = {
    "event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076",
    "event_type": "UPDATED",
    "attributes_changed": "['metadataStatus', 'elements']",
}
df = pd.DataFrame(data=sample, index=[0])
df["attributes_changed"] = df["attributes_changed"].apply(eval)
df_with_seq_id = [
    (json.dumps(rec), idx) for (idx, rec) in df.to_dict(orient="index").items()
]

This produce the following array:这会产生以下数组:

[('{"event_id": "dd9726c4-9c22-47b3-9a1b-fd6ecf494076", "event_type": "UPDATED", "attributes_changed": ["metadataStatus", "elements"]}',
  0)]

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

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