使用 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

我想用同样的方法创建这样的东西 table:

通过 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 和 Product,然后转换结果。

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')

结果: