首页 > 解决方案 > Pandas Dataframe 用 stack 和 unstack 重塑

问题描述

我正在尝试弄乱熊猫堆栈和取消堆栈。我想知道是否有可能以这种方式重塑我的数据。

这是我正在练习的示例数据。

ID,Value1,Value2
1,3,12
1,4,13
1,5,14
1,6,15
1,7,16
2,8,17
2,9,18
2,10,19
2,11,20

我想以这种方式重塑。

ID 
1   Index(Extra Column) Value1, value2
    1                      3    12
    2                      4    13
    3                      5    14
    4                      6    15
    5                      7    16

2
    1                      8    17
    2                      9    18
    3                      10   19
    4                      11   20

我试过这个

df1 = pd.DataFrame(df[['Value1', 'Value2']], index= df['ID']).stack()

或者

df1 = df.set_index(['ID']).stack()

这会将 Value1 和 Value2 从列更改为我不想要的行。

有任何想法吗 ?

标签: pythonpandasdataframe

解决方案


我在这里建议set_index+ cumcount

df.set_index(['ID', df.groupby('ID').cumcount() + 1])

      Value1  Value2
ID                  
1  1       3      12
   2       4      13
   3       5      14
   4       6      15
   5       7      16
2  1       8      17
   2       9      18
   3      10      19
   4      11      20

另一种选择是使用concat

pd.concat({k : g.reset_index(drop=True) for k, g in df.drop('ID', 1).groupby(df.ID)})

     Value1  Value2
1 0       3      12
  1       4      13
  2       5      14
  3       6      15
  4       7      16
2 0       8      17
  1       9      18
  2      10      19
  3      11      20

推荐阅读