簡體   English   中英

Pandas:如何在 groupby 和 unstack 之后刪除索引列?

[英]Pandas: How to remove the index column after groupby and unstack?

在 groupby 並取消堆疊 DataFrame 之后,我無法刪除 pandas 中的索引列。

我原來的 DataFrame 是這樣的:

example = pd.DataFrame({'date': ['2016-12', '2016-12', '2017-01', '2017-01', '2017-02', '2017-02', '2017-02'], 'customer': [123, 456, 123, 456, 123, 456, 456], 'sales': [10.5, 25.2, 6.8, 23.4, 29.5, 23.5, 10.4]})
example.head(10)

output:

日期 顧客 銷售量
0 2016-12 123 10.5
1 2016-12 456 25.2
2 2017-01 123 6.8
3 2017-01 456 23.4
4 2017-2 123 29.5
5 2017-2 456 23.5
6 2017-2 456 10.4

請注意,一個客戶每月可以進行多次銷售(如第 5 行和第 6 行)。

我的目標是將 DataFrame 轉換為聚合的 DataFrame,如下所示:

顧客 2016-12 2017-01 2017-02
123 10.5 6.8 29.5
234 25.2 23.4 33.9

到目前為止我的解決方案:

example = example[['date', 'customer', 'sales']].groupby(['date', 'customer']).sum().unstack('date')
example.head(10)

output:

銷售量
日期 2016-12 2017-01 2017-02
顧客
123 10.5 6.8 29.5
234 25.2 23.4 33.9
example = example['sales'].reset_index(level=[0])
example.head(10)

output:

日期 顧客 2016-12 2017-01 2017-02
0 123 10.5 6.8 29.5
1 234 25.2 23.4 33.9



此時我無法刪除“日期”列:

example.reset_index(drop = True)
example.head()

output:

日期 顧客 2016-12 2017-01 2017-02
0 123 10.5 6.8 29.5
1 234 25.2 23.4 33.9

它只是保持不變。 你有什么想法嗎?

您的解決方案的替代方案,但關鍵是添加一個rename_axis(columns = None) ,因為date是列軸的名稱:

(example[["date", "customer", "sales"]]
.groupby(["date", "customer"])
.sum()
.unstack("date")
.droplevel(0, axis="columns")
.rename_axis(columns=None)
.reset_index())

    customer    2016-12 2017-01 2017-02
0   123          10.5   6.8     29.5
1   456          25.2   23.4    33.9

為什么不直接 go 與pivot_table

(example
 .pivot_table('sales', index='customer', columns="date", aggfunc='sum')
 .rename_axis(columns=None).reset_index())
    
    customer    2016-12 2017-01 2017-02
0   123         10.5    6.8     29.5
1   456         25.2    23.4    33.9

暫無
暫無

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

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