我有一個 csv 檔案,其中有列 df['questions'] 和 JSON 資料
| Date | Agent Name | Questions |
| 8/5/2022 | Alaa M | the specified column in question please view the example below |
| 8/5/2022 | Othman M | the specified column in question please view the example below |
該列中的資料示例
[ {'id': 'dee52266-c096-47f4-96d4-6346498039ee', 'name': '1.G - 是否提出了問題?', 'displayOrder': 13, 'type': 'choice', ' multiSelect': False, 'questionsResponseModel': [{'id': 'a3e0ac59-5cc1-4654-a6bc-fbc71d86ba25', 'name': 'No'}], 'parentGroup': 'f1654f7c-204f-48d0-b940- ee9bb98eafa0','score':'0','maxScore':'0','percentage':'0'},{'id':'6b0a92b4-fad9-488d-8296-030799ee00eb','name':' 1.G - 評論','displayOrder':14,'type':'text','multiSelect':無,'questionsResponseModel':'NA','parentGroup':'f1654f7c-204f-48d0-b940-ee9bb98eafa0' , '分數': '0','maxScore':'0','百分比':'0'}]
import pandas as pd
import numpy as np
df = pd.read_csv('Desktop\Data.csv')
#first I tried to replace ' to " to view it as JSON however it is not working
def js(row):
#return row['questions'].lower().replace("'", '"')
df['new_questions'] = df.apply(js, axis=1)
df["new_questions_2"] = df["new_questions"].apply(json.loads)
#second tried to apply pd.series which also does not work
out = (df.drop(columns=['questions'])
.join(df['questions'].apply(pd.Series).add_prefix('questions_'))
)
uj5u.com熱心網友回復:
嘗試:
import ast
df["Questions"] = df["Questions"].apply(ast.literal_eval)
df = df.explode("Questions")
df = pd.concat([df, df.pop("Questions").apply(pd.Series)], axis=1)
df = df.explode("questionsResponseModel")
df = pd.concat(
[df, df.pop("questionsResponseModel").apply(pd.Series).add_prefix("qrm_")],
axis=1,
)
df = df.drop(columns="qrm_0")
print(df)
印刷:
Date Agent Name id name displayOrder type multiSelect parentGroup score maxScore percentage qrm_id qrm_name
0 8/5/2022 Alaa M dee52266-c096-47f4-96d4-6346498039ee 1.G – Did an issue been raised? 13 choice False f1654f7c-204f-48d0-b940-ee9bb98eafa0 0 0 0 a3e0ac59-5cc1-4654-a6bc-fbc71d86ba25 No
0 8/5/2022 Alaa M 6b0a92b4-fad9-488d-8296-030799ee00eb 1.G - Comment 14 text None f1654f7c-204f-48d0-b940-ee9bb98eafa0 0 0 0 NaN NaN
1 8/5/2022 Othman M dee52266-c096-47f4-96d4-6346498039ee 1.G – Did an issue been raised? 13 choice False f1654f7c-204f-48d0-b940-ee9bb98eafa0 0 0 0 a3e0ac59-5cc1-4654-a6bc-fbc71d86ba25 No
1 8/5/2022 Othman M 6b0a92b4-fad9-488d-8296-030799ee00eb 1.G - Comment 14 text None f1654f7c-204f-48d0-b940-ee9bb98eafa0 0 0 0 NaN NaN
編輯: “爆炸”questionsResponseModel列也是。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504579.html
