仅从数据框转置少量列和行

时间:2018-05-29 01:13:51

标签: python pandas dataframe

我希望通过保持起始列的固定来转换我的数据框中的某些列及其值。

I / P帧:

SET /A cutSpaceCount=substringLength+1

O / P框架:

Type    Class   24/01/2018  25/01/2018  26/01/2018
Plant1  Plant   5498    5998    5815
Plant2  Plant   3416    4844    4991
Veg1    Vegetable   5426    5464    3756
Veg2    Vegetable   5317    4616    7528

我通常在excel中执行此操作,并尝试在pandas中使用pivot但无法实现它的想法。任何人都可以帮我带头吗?

由于

1 个答案:

答案 0 :(得分:2)

melt

df.melt(['Type', 'Class'], var_name='Date', value_name='Value')

      Type      Class        Date  Value
0   Plant1      Plant  24/01/2018   5498
1   Plant2      Plant  24/01/2018   3416
2     Veg1  Vegetable  24/01/2018   5426
3     Veg2  Vegetable  24/01/2018   5317
4   Plant1      Plant  25/01/2018   5998
5   Plant2      Plant  25/01/2018   4844
6     Veg1  Vegetable  25/01/2018   5464
7     Veg2  Vegetable  25/01/2018   4616
8   Plant1      Plant  26/01/2018   5815
9   Plant2      Plant  26/01/2018   4991
10    Veg1  Vegetable  26/01/2018   3756
11    Veg2  Vegetable  26/01/2018   7528

set_index + stack

(df.set_index(['Type', 'Class'])
   .stack()
   .rename_axis(['Type', 'Class', 'Date'])
   .reset_index(name='Value')
)

      Type      Class        Date  Value
0   Plant1      Plant  24/01/2018   5498
1   Plant1      Plant  25/01/2018   5998
2   Plant1      Plant  26/01/2018   5815
3   Plant2      Plant  24/01/2018   3416
4   Plant2      Plant  25/01/2018   4844
5   Plant2      Plant  26/01/2018   4991
6     Veg1  Vegetable  24/01/2018   5426
7     Veg1  Vegetable  25/01/2018   5464
8     Veg1  Vegetable  26/01/2018   3756
9     Veg2  Vegetable  24/01/2018   5317
10    Veg2  Vegetable  25/01/2018   4616
11    Veg2  Vegetable  26/01/2018   7528