【问题标题】:Creating one dataframe from another (using pivot)从另一个数据框创建一个数据框(使用数据透视)
【发布时间】:2016-08-20 06:45:46
【问题描述】:

我遇到了熊猫问题。我有一个包含三列的数据框:'id1'、'id2'、'amount'。

由此,我想创建另一个数据框,其索引为“id1”,列为“id2”,并且单元格包含相应的“金额”。

举个例子:

import pandas as pd
df = pd.DataFrame([['first_person','first_item',10],['first_person','second_item',6],['second_person','first_item',18],['second_person','second_item',36]],columns = ['id1','id2','amount'])

产生:

     id1              id2             amount
0    first_person     first_item      10
1    first_person     second_item     6
2    second_person    first_item      18
3    second_person    second_item     36

由此我想创建第二个数据框:

                 first_item    second_item
first_person     10            6
second_person    18            36

当然,在发布之前,我已经研究了一段时间,但我为此所做的只是一个双重“for循环”......对于我的数据框的大小来说,这是无法计算的.你知道如何以更 Pythonic 的方式做到这一点吗? (这显然比'for'循环更有效!)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我认为您可以将pivot 与rename_axis 一起使用(pandas 0.18.0 中的新功能):

    print df
                 id1          id2  amount
    0   first_person   first_item      10
    1   first_person  second_item       6
    2  second_person   first_item      18
    3  second_person  second_item      36
    
    print df.pivot(index='id1', columns='id2', values='amount')
            .rename_axis(None)
            .rename_axis(None, axis=1)
    
                   first_item  second_item
    first_person           10            6
    second_person          18           36
    

    【讨论】:

    • 它似乎完全符合我的需要!执行该重命名索引问题。实际上,'.rename_axis(None)' 方法返回以下错误:'must pass an index to rename'(如果重要的话,我在 Python 2.7 下)。
    • pandas 的版本是什么? print pd.show_versions()
    • 0.17.1 这解释了为什么 rename_axis 不起作用。
    • 如果可以更新,请使用df.index.name = None和df.columns.names = None
    • 没有更新我在另一篇文章中发现:stackoverflow.com/questions/29765548/… 这非常适合擦除索引和列名。谢谢你的枢轴技巧,它对我帮助很大!
    猜你喜欢
    • 2018-12-30
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多