我的資料框位于以下結構中。我想根據詳細資訊列中的嵌套值來打破它們
cust_id, name, details
101, Kevin, [{"id":1001,"country":"US","state":"OH"}, {"id":1002,"country":"US","state":"GA"}]
102, Scott, [{"id":2001,"country":"US","state":"OH"}, {"id":2002,"country":"US","state":"GA"}]
預期輸出
cust_id, name, id, country, state
101, Kevin, 1001, US, OH
101, Kevin, 1002, US, GA
102, Scott, 2001, US, OH
102, Scott, 2002, US, GA
uj5u.com熱心網友回復:
df = df.explode('details').reset_index(drop=True)
df = df.merge(pd.json_normalize(df['details']), left_index=True, right_index=True).drop('details', axis=1)
df.explode("details")基本上重復detailsN 次中的每一行,其中 N 是該details行的陣列(如果有)中的專案數- 由于
explode重復行,原始行的索引(0 和 1)被復制到新行,因此它們的索引是 0、0、1、1,這會擾亂后面的處理。reset_index()為索引創建一個新列,從 開始0。drop=True使用是因為默認情況下,pandas 將保留舊的索引列;這將洗掉它。 pd.json_normalize(df['details'])將列(其中每行包含一個 JSON 物件)轉換為新資料幀,其中所有 JSON 物件的每個唯一鍵都是新列df.merge()將新資料幀合并到原始資料幀中left_index=True并right_index=True告訴 Pandas 將指定的資料幀從它的第一行開始合并到這個資料幀中,從它的第一行開始.drop('details', axis=1)擺脫details包含舊物件的舊列
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/353666.html
標籤:熊猫
上一篇:找到值時如何提取整行
