繁体   English   中英

使用python中的三列组合在数据框中创建新列

[英]Create new columns in a dataframe with combination of three columns in python

我有这样的事情:

       Date  Id  Product  Sales
0  1/1/2001   1       21      1200
1  1/1/2001   1       22      1000
2  1/1/2001   1       23      1500
3  2/1/2001   1       21      300
4  2/1/2001   2       22      200
5  3/1/2001   3       21      400
6  4/1/2001   3       22      500

我想用同一张表创建类似的东西:

在此处输入图片说明

通过Pandas的Pivot功能很容易做到这一点。

这是您的数据框:

df=pd.DataFrame([['1/1/2001',1,21,1200],['1/1/2001',1,22,1000],['1/1/2001',1,23,1500],['2/1/2001',1,21,300],['2/1/2001',2,22,200],['3/1/2001',3,21,400],['4/1/2001',3,22,500]],columns=('Date','Id','Product','Sales'))

输出:

    Date    Id  Product Sales
0   1/1/2001    1   21  1200
1   1/1/2001    1   22  1000
2   1/1/2001    1   23  1500
3   2/1/2001    1   21  300
4   2/1/2001    2   22  200
5   3/1/2001    3   21  400
6   4/1/2001    3   22  500

现在只需使用以下代码:

df.pivot(index='Date',columns='Product',values='Sales')

您会得到:

Product      21     22      23
Date            
1/1/2001    1200.0  1000.0  1500.0
2/1/2001    300.0   200.0   NaN
3/1/2001    400.0   NaN     NaN
4/1/2001    NaN     500.0   NaN

关于列的名称,那么,您可以更改它的方式,也可以更改它们在我的答案中的显示方式,我想它们还可以。

您将串联ID和产品,然后透视结果。

import pandas as pd

df=pd.DataFrame([['1/1/2001',1,21,1200],['1/1/2001',1,22,1000],['1/1/2001',1,23,1500],['2/1/2001',1,21,300],['2/1/2001',2,22,200],['3/1/2001',3,21,400],['4/1/2001',3,22,500]],columns=('Date','Id','Product','Sales'))

df['Id_Prod'] = df['Id'].astype(str).str.cat(df['Product'].astype(str), sep='_')

df.pivot(index='Date',columns='Id_Prod',values='Sales')

结果:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM