将pandas数据框索引重塑为列

Sir*_* S. 2 python pivot-table dataframe pandas

考虑下面的pandas Series对象,

index = list('abcdabcdabcd')
df = pd.Series(np.arange(len(index)), index = index)
Run Code Online (Sandbox Code Playgroud)

我想要的输出是

   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
Run Code Online (Sandbox Code Playgroud)

我对pd.pivot_table和pd.unstack付出了一些努力,而解决方案可能在于正确使用其中之一。我最接近的是

df.reset_index(level = 1).unstack(level = 1)
Run Code Online (Sandbox Code Playgroud)

但这没有给我我想要的输出

//这甚至更接近所需的输出,但是我无法处理索引分组。

df.to_frame().set_index(df1.values, append = True, drop  = False).unstack(level = 0)

     a    b     c     d
0   0.0  NaN   NaN   NaN
1   NaN  1.0   NaN   NaN
2   NaN  NaN   2.0   NaN
3   NaN  NaN   NaN   3.0
4   4.0  NaN   NaN   NaN
5   NaN  5.0   NaN   NaN
6   NaN  NaN   6.0   NaN
7   NaN  NaN   NaN   7.0
8   8.0  NaN   NaN   NaN
9   NaN  9.0   NaN   NaN
10  NaN  NaN  10.0   NaN
11  NaN  NaN   NaN  11.0
Run Code Online (Sandbox Code Playgroud)

roo*_*oot 5

使用一些更通用的解决方案cumcount来获取新的索引值并pivot进行重塑:

# Reset the existing index, and construct the new index values.
df = df.reset_index()
df.index = df.groupby('index').cumcount()

# Pivot and remove the column axis name.
df = df.pivot(columns='index', values=0).rename_axis(None, axis=1)
Run Code Online (Sandbox Code Playgroud)

结果输出:

   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
Run Code Online (Sandbox Code Playgroud)