【问题标题】:Convert dictionary from wide to long form using pandas使用 pandas 将字典从宽格式转换为长格式
【发布时间】:2018-04-29 02:09:16
【问题描述】:

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

[ {'回应':1,'工作生活':5,'生活家庭':2,'家庭平衡':10}, {'Response': 2, '鼓励管理': 11, '管理职业': 1, '职业抱负': 4, '抱负发展': 8},{'Response': 3, 'encourage people': 15, 'people manager': 9, 'managers ask': 5, 'ask employees': 9} ]

应该变成三列数据框

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

【问题讨论】:

    标签: python pandas dictionary dataframe pandas-groupby


    【解决方案1】:

    这可能是您正在寻找的。使用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 是您的字典数据。请记住,字典没有排序,因此总是期望与您的问题相同的顺序是不合理的。

    【讨论】:

    • 你太棒了...谢谢!!
    • @ZainAbbas 你也是...如果你accept my answer (-;
    猜你喜欢
    • 2018-01-31
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多