使用 pandas 将字典从宽格式转换为长格式

Convert dictionary from wide to long form using pandas

我在 Python 中有一个字典列表,其中包含不同的键(所有键都存在响应键),我想将其转换为 Panda Dataframe,以便所有键值都显示为带有 Response 键值作为列重复。例如,以下列表

[ {'响应':1,'work life':5,'life family':2,'family balance': 10}, {'响应': 2, 'encouragement management': 11, 'management career': 1, 'career aspirations': 4, 'aspirations develop': 8}, {'响应': 3, 'encourage people': 15, 'people managers': 9, 'managers ask': 5, 'ask employees': 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 是你的字典数据。请记住,字典 未排序 ,因此始终期望与您的问题中的顺序相同是不合理的。