【问题标题】:Pandas: reshaping a dataframe with duplicate entriesPandas:使用重复条目重塑数据框
【发布时间】:2018-06-10 12:11:07
【问题描述】:

我有一个名为 df 的 Pandas DF(下面是简短的 sn-p)

    deathtype    height    deaths
0   AMS           4900       1
1   AMS           5150       1
2   AMS           5300       1
3   Avalanche     5350       14
4   Avalanche     5600       4
5   Avalanche     5700       1
6   Avalanche     5800       17
7   Unexplained   8500       1
8   Unexplained   8560       1

我正在尝试将数据重塑为以下内容;

deaths         1                4          14       17
deathtype               
AMS           4900,5150,5300    0          0        0
Avalanche     5700              5600       5350     5800
Unexplained   8500, 8560        0          0        0

我知道 pivot_table 无法实现这一点,因为 aggfunc 使用重复值的平均值,这意味着对于所有为 1 的 deaths 值,均值将被记录。 Pivot_table 给了我以下信息;

df.pivot_table(index='deathtype', columns='deaths', values='height', fill_value='0')

deaths           1              4      14     17
deathtype               
AMS           5116.666667       0      0      0
Avalanche     5700.000000       5600   5350   5800
Unexplained   8530.000000       0      0      0

我正在寻找有关如何执行此操作的建议。看起来 pivot_table 不是正确的方法。谁能指点一下。

【问题讨论】:

    标签: python pandas dataframe reshape


    【解决方案1】:

    使用groupbyjoin 聚合,然后通过unstack 重塑:

    d = lambda x: ', '.join(x.astype(str))
    df = df.groupby(['deathtype', 'deaths'])['height'].agg(d).unstack(fill_value='0')
    print (df)
    deaths                     1     4     14    17
    deathtype                                      
    AMS          4900, 5150, 5300     0     0     0
    Avalanche                5700  5600  5350  5800
    Unexplained        8500, 8560     0     0     0
    

    详情

    print (df.groupby(['deathtype', 'deaths'])['height'].agg(lambda x: ', '.join(x.astype(str))))
    deathtype    deaths
    AMS          1         4900, 5150, 5300
    Avalanche    1                     5700
                 4                     5600
                 14                    5350
                 17                    5800
    Unexplained  1               8500, 8560
    Name: height, dtype: object
    

    pivot_table 的另一个解决方案:

    df = df.pivot_table(index='deathtype', 
                        columns='deaths', 
                        values='height', 
                        fill_value='0', 
                        aggfunc=lambda x: ', '.join(x.astype(str)))
    

    【讨论】:

    • jezrael - 非常感谢您展示了这两种方法。这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多