[問題]Dataframe json 資料處理

看板Python作者 (【積π】)時間2年前 (2022/01/26 22:14), 2年前編輯推噓3(303)
留言6則, 2人參與, 2年前最新討論串1/1
想請問各位前輩 該如何把result欄位內 json格式展開後再合併至原本的dataframe import pandas as pd df = pd.read_csv('Poker.txt', sep='\t') df['result'] 這邊之後就不知道怎麼操作了 麻煩各位前輩了 或是給我關鍵字我去google查詢 謝謝各位前輩 資料如下 ------------------------------------------------ id math english result 0 100 80 {"info":"pass","avg":"90","level":"A"} 1 50 40 {"info":"fail","avg":"45","level":"E"} 2 60 70 {"info":"pass","avg":"65","level":"D"} ------------------------------------------------ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.161.186.48 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1643206473.A.F56.html ※ 編輯: ctr1 (118.161.186.48 臺灣), 01/26/2022 22:18:43

01/26 22:23, 2年前 , 1F
df_res = pd.DataFrame(df.result.values.tolist())
01/26 22:23, 1F

01/26 22:23, 2年前 , 2F
df = df.drop("result",axis=1).join(df_res)
01/26 22:23, 2F
※ 編輯: ctr1 (118.161.186.48 臺灣), 01/26/2022 22:33:35

01/26 22:35, 2年前 , 3F
抱歉 我改一下格式有誤><
01/26 22:35, 3F
※ 編輯: ctr1 (118.161.186.48 臺灣), 01/26/2022 22:38:15

01/26 22:45, 2年前 , 4F
你result是string嗎還是dict?
01/26 22:45, 4F

01/26 22:48, 2年前 , 5F
string要先import json; df.result.apply(json.loads)
01/26 22:48, 5F

01/26 22:48, 2年前 , 6F
後面一樣接著.values.tolist() 接回原本df就好
01/26 22:48, 6F
文章代碼(AID): #1XyLT9zM (Python)
文章代碼(AID): #1XyLT9zM (Python)