Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 透视/取消堆栈具有重复条目的数据帧,而不进行聚合_Python_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 透视/取消堆栈具有重复条目的数据帧,而不进行聚合

Python 透视/取消堆栈具有重复条目的数据帧,而不进行聚合,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,因此,我得到了如下数据帧: Col_0 Col_1 Index_1 A 0 2 A 3 1 A 2 2 B 3 1 B 4 3 B 5 1 我想将其重塑为以下格式: Col_0 Col_1 A B A B 0 3 2 1

因此,我得到了如下数据帧:

        Col_0 Col_1
Index_1        
      A     0     2
      A     3     1
      A     2     2
      B     3     1
      B     4     3
      B     5     1
我想将其重塑为以下格式:

    Col_0     Col_1
    A    B    A    B
    0    3    2    1
    3    4    1    3
    2    5    2    1

我尝试了
pandas.pivot
pandas.unstack
pandas.groupby
。这些都不管用。有人能帮我吗?非常感谢。

使用
cumcount
创建索引,然后
pivot

df['idx'] = df.groupby(df.index).cumcount()
df.reset_index().pivot(index='idx', columns='Index_1').rename_axis(None)
输出:

        Col_0    Col_1   
Index_1     A  B     A  B
0           0  3     2  1
1           3  4     1  3
2           2  5     2  1

使用
cumcount
创建索引,然后使用
pivot

df['idx'] = df.groupby(df.index).cumcount()
df.reset_index().pivot(index='idx', columns='Index_1').rename_axis(None)
输出:

        Col_0    Col_1   
Index_1     A  B     A  B
0           0  3     2  1
1           3  4     1  3
2           2  5     2  1