簡體   English   中英

使用熊貓將字典從寬格式轉換為長格式

[英]Convert dictionary from wide to long form using pandas

我有一個使用不同鍵的Python字典列表(所有中都存在Response Key),我想將其轉換為Panda Dataframe,以便所有鍵值都顯示為行,並且Response Key值重復作為列。 例如,以下列表

[ {' 回應 ':1,'工作生活':5,'生活家庭':2,'家庭平衡':10},{' 回應 ':2,'鼓勵管理':11,'管理職業':1 ,“職業理想”:4,“理想發展”:8},{“ 響應 ”:3,“鼓勵人”:15,“人經理”:9,“經理問”:5,“問員工”:9 } ]

應該成為3列數據框,因為

Response | Attribute | Value
1, work life, 5
1, life family, 2
1, family balance, 10
2, encouragement management, 11
2, management career, 1
2, career aspirations, 4
2, aspirations develop, 8
3, encourage people, 15
3, people managers, 9
3, managers ask, 5
3, ask employees, 9

這可能是您要尋找的。 使用stack ,然后重置索引和列名稱。

df = pd.DataFrame(d).set_index('Response').stack().reset_index()
df.columns = ['Response', 'Attribute', 'Value']

df

    Response                 Attribute  Value
0          1            family balance   10.0
1          1               life family    2.0
2          1                 work life    5.0
3          2       aspirations develop    8.0
4          2        career aspirations    4.0
5          2  encouragement management   11.0
6          2         management career    1.0
7          3             ask employees    9.0
8          3          encourage people   15.0
9          3              managers ask    5.0
10         3           people managers    9.0

d是您的詞典數據。 請記住,字典不是有序的 ,因此總是期望與您的問題相同的順序是不合理的。

暫無
暫無

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

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