问题描述
我有一个数据框,其中包含不同年份不同时间段内每种产品的销售额:
df = pd.DataFrame({'Product': {0: '1',1: '1',2: '2',3: '2'},'Year': {0: 2000,1: 2001,2: 2001,3:2002},'Jan-Feb': {0: 2,1: 4,2: 2,3:4},'Mar-Apr': {0: 1,1: 2,2: 1,3:6}})
df
的产品中,每个year
的产品1和2的销售额,但一年内的时间段显示在不同的列中。在此示例中,我提供了两列,但还有四列代表一年中连续两个月的剩余期间。
我想将df
重塑成这样:
df2 = pd.DataFrame({'Product': {0: '1',2: '1',3: '1',4: '2',5: '2',6: '2',7: '2'},1: 2000,3:2001,4: 2001,5: 2001,6: 2002,7:2002},'Period': {0: 'Jan-Feb',1: 'Mar-Apr',2: 'Jan-Feb',3:'Mar-Apr',4: 'Jan-Feb',5: 'Mar-Apr',6: 'Jan-Feb',7:'Mar-Apr'},'Sales': {0: 2,1: 1,2: 4,3: 2,4: 2,5: 1,6: 4,7: 6}})
在这种情况下,月期间全部位于一列中,而销售则位于另一列中。我尝试了各种形式的重塑,但显然找不到某些东西,因为我没有成功找到能满足我要求的东西。
解决方法
使用melt
out = df.melt(['Product','Year'],var_name = 'Period',value_name = 'Sales')
Product Year Period Sales
0 1 2000 Jan-Feb 2
1 1 2001 Jan-Feb 4
2 2 2001 Jan-Feb 2
3 2 2002 Jan-Feb 4
4 1 2000 Mar-Apr 1
5 1 2001 Mar-Apr 2
6 2 2001 Mar-Apr 1
7 2 2002 Mar-Apr 6
,
使用while True:
userinput = input( 'type exit to exit' )
if userinput != 'exit':
print("Please enter individual specimen data: ")
...
:
stack()
输出:
df = df.set_index(['Product','Year']).stack(0).reset_index()
df.columns = ['Product','Year','Period','Sales']