Pandas,多索引
Pandas, mulitindexing
我有数据需要按列聚合,然后再按列聚合。我需要的是每个唯一客户每个产品类别的总支出。 Multiindex 应该这样做。问题是我是 Pandas 的新手,我不了解多索引。
我的数据结构如下:
Customer Products Amount
1 001 Toys 5
2 002 Toys 6
3 002 Cars 7
4 001 Toys 2
5 001 Cars 9
我需要这样的:
Customers Products Sum of ammount
001 Toys 7
Cars 9
002 Toys 6
Cars 7
稍后我需要对其进行转换,以便我可以获得每个客户每个产品类别的总支出。
Customer Toys Cars
001 7 9
002 6 7
我一直在研究代码,但卡住了。一直在阅读,但没有找到我正在寻找的内容。
df1 = df.groupby(['Customer','Products'])['Amount'].sum().reset_index(name='Sum of ammount')
print (df1)
Customer Products Sum of ammount
0 001 Cars 9
1 001 Toys 7
2 002 Cars 7
3 002 Toys 6
然后你可以使用 pivot
从 df1
:
print (df1.pivot(index='Customer',columns='Products',values='Sum of ammount'))
Products Cars Toys
Customer
001 9 7
002 7 6
如果需要 pivot_table
来自 df
:
print (df.pivot_table(index='Customer',columns='Products',values='Amount', aggfunc=sum))
Products Cars Toys
Customer
001 9 7
002 7 6
编辑:
为了更好 df
你可以 reset_index
with rename_axis
(pandas
0.18.0
中的新功能):
print (df.pivot_table(index='Customer',columns='Products',values='Amount', aggfunc=sum)
.reset_index()
.rename_axis(None, axis=1))
Customer Cars Toys
0 001 9 7
1 002 7 6
print (df1.pivot(index='Customer',columns='Products',values='Sum of ammount')
.reset_index()
.rename_axis(None, axis=1))
Customer Cars Toys
0 001 9 7
1 002 7 6
我有数据需要按列聚合,然后再按列聚合。我需要的是每个唯一客户每个产品类别的总支出。 Multiindex 应该这样做。问题是我是 Pandas 的新手,我不了解多索引。
我的数据结构如下:
Customer Products Amount
1 001 Toys 5
2 002 Toys 6
3 002 Cars 7
4 001 Toys 2
5 001 Cars 9
我需要这样的:
Customers Products Sum of ammount
001 Toys 7
Cars 9
002 Toys 6
Cars 7
稍后我需要对其进行转换,以便我可以获得每个客户每个产品类别的总支出。
Customer Toys Cars
001 7 9
002 6 7
我一直在研究代码,但卡住了。一直在阅读,但没有找到我正在寻找的内容。
df1 = df.groupby(['Customer','Products'])['Amount'].sum().reset_index(name='Sum of ammount')
print (df1)
Customer Products Sum of ammount
0 001 Cars 9
1 001 Toys 7
2 002 Cars 7
3 002 Toys 6
然后你可以使用 pivot
从 df1
:
print (df1.pivot(index='Customer',columns='Products',values='Sum of ammount'))
Products Cars Toys
Customer
001 9 7
002 7 6
如果需要 pivot_table
来自 df
:
print (df.pivot_table(index='Customer',columns='Products',values='Amount', aggfunc=sum))
Products Cars Toys
Customer
001 9 7
002 7 6
编辑:
为了更好 df
你可以 reset_index
with rename_axis
(pandas
0.18.0
中的新功能):
print (df.pivot_table(index='Customer',columns='Products',values='Amount', aggfunc=sum)
.reset_index()
.rename_axis(None, axis=1))
Customer Cars Toys
0 001 9 7
1 002 7 6
print (df1.pivot(index='Customer',columns='Products',values='Sum of ammount')
.reset_index()
.rename_axis(None, axis=1))
Customer Cars Toys
0 001 9 7
1 002 7 6