簡體   English   中英

將帶有字典的列表的 Dataframe 列轉換為單獨的列並展開 Dataframe

[英]Convert Dataframe column of list with dictionaries into seperate columns and expand Dataframe

我是 Pandas Dataframe 的新手,並設法完成了一些事情,但我完全被這個問題所困擾:

我有一個如下所示的數據框表:

ID 價格 店鋪
0 1 7 [{code:{location: 'beach', guest: '300'}, text:{textvalue:'beautiful'}},{code:{location: '森林', guest: '200'}, text:{textvalue :'遠處'}}]
1 1 8 [{code:{location: 'beach', guest: '500'}, text:{textvalue:'overcrowded'}},{code:{location: 'forest', guest: '200'}, text:{textvalue :'遠處'}}]
2 2 9 [{code:{location: 'mountain', guest: '300'}, text:{textvalue:'cold at night'}}]
3 2 7 []

我想在“商店”列中展開列表。 如果列表不為空,那么我想獲取“位置”和“文本值”。 因為有時列表中有多個字典,我想用每個 id 一個位置/文本值來使表格更長。

所以它看起來像:

ID 價格 店鋪位置 shop.textvalue
0 1 7 海灘 美麗的
1 1 7 森林 遠處
2 1 8 海灘 人滿為患
3 1 8 森林 遠處
4 2 9 太冷
5 2 7 不適用 不適用

我嘗試了很多不同的方法,使用 .explode()。 apply() 和迭代。 但我還沒有找到解決辦法。 歡迎任何幫助

目前尚不清楚您的輸入數據的外觀以及它是否有效,但您也可以使用dataframe pandas.normalize()將嵌套的JSON或字典列表讀取到數據框。

pd.json_normalize(data, 'shop', ['id','price'])
例子
data = [
    {
    'id':1,
    'price':7,
    'shop':[{'code':{'location': 'beach', 'guests': '300'}, 'text':{'textvalue':'beautiful'}},{'code':{'location': 'forest', 'guests': '200'}, 'text':{'textvalue':'far away'}}]
    },
    {
    'id':1,
    'price':8,
    'shop':[{'code':{'location': 'beach', 'guests': '500'}, 'text':{'textvalue':'overcrowded'}},{'code':{'location': 'forest', 'guests': '200'}, 'text':{'textvalue':'far away'}}]
    }
]

import pandas as pd

df = pd.json_normalize(data, 'shop', ['id','price'])
df = df[df.columns.tolist()[-2:] + df.columns.tolist()[:-2]]
df.columns = [c.replace('code','shop') for c in df.columns]
df
輸出
ID 價格 店鋪位置 shop.guests 文本.文本值
0 1 7 海灘 300 美麗的
1 1 7 森林 200 遠處
2 1 8 海灘 500 人滿為患
3 1 8 森林 200 遠處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM