重塑 pandas 数据帧将一行反转为多列

reshape pandas dataframe reversing one row into several columns

我有一个数据框,如下所示。它包含 ID 列、月份以及客户是否购买了特定产品。

ID      Date     Buy_Or_Not
1       2016-01       1
1       2016-02       1
1       2016-03       0
1       2016-04       1
1       2016-05       0
2       2016-01       1
2       2016-02       1
2       2016-03       1
2       2016-04       1
2       2016-05       0

我想将它重塑成这样。

ID      2016-01 2016-02 2016-03 2016-04 2016-05
1       1       1       0       1       0
2       1       1       1       1       0

完成这项工作的任何建议。

使用pivot:

df = df.pivot(index='ID', columns='Date', values='Buy_Or_Not')
print (df)
Date  2016-01  2016-02  2016-03  2016-04  2016-05
ID                                               
1           1        1        0        1        0
2           1        1        1        1        0

如果错误如下:

ValueError: Index contains duplicate entries, cannot reshape

使用pivot_table.

这里有3种整形方法

1) 使用 pd.pivot

In [58]: df.pivot(index='ID', columns='Date', values='Buy_Or_Not')
Out[58]:
Date  2016-01  2016-02  2016-03  2016-04  2016-05
ID
1           1        1        0        1        0
2           1        1        1        1        0

2) 使用 pd.crosstab

In [59]: pd.crosstab(df['ID'], df['Date'], df['Buy_Or_Not'], aggfunc=sum)
Out[59]:
Date  2016-01  2016-02  2016-03  2016-04  2016-05
ID
1           1        1        0        1        0
2           1        1        1        1        0

3) 使用 groupby and unstack

In [60]: df.groupby(['ID', 'Date']).sum().unstack('Date')
Out[60]:
     Buy_Or_Not
Date    2016-01 2016-02 2016-03 2016-04 2016-05
ID
1             1       1       0       1       0
2             1       1       1       1       0