2017-04-21 176 views
1

考虑下面的熊猫系列对象,重塑熊猫据帧索引列

index = list('abcdabcdabcd') 
df = pd.Series(np.arange(len(index)), index = index) 

我期望的输出,

a b c d 
0 0 1 2 3 
1 4 5 6 7 
2 8 9 10 11 

我已经把一些努力与pd.pivot_table,pd.unstack和解决方法可能在于正确使用其中的一个。我已经达到最接近的是

df.reset_index(level = 1).unstack(level = 1) 

但这并不甚至接近所需的输出给了我我我寻找

输出//这里是什么东西,但我不能够处理索引分组。

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 

回答

3

更一般的位使用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) 

输出结果:

a b c d 
0 0 1 2 3 
1 4 5 6 7 
2 8 9 10 11 
+0

哇!很聪明 ! – MaxU

+0

确实很周到 –

0

这里是一个方式,如果索引总是以同样的顺序循环,将工作,而且你知道“月经”(在这种情况下,4):

>>> pd.DataFrame(df.values.reshape(-1,4), columns=list('abcd')) 
    a b c d 
0 0 1 2 3 
1 4 5 6 7 
2 8 9 10 11 
>>> 
+0

索引循环将按照相同的顺序。但是,索引长度不一定可以被4整除,例如['a','b','a','b','a']不能在numpy中重新排列成一个(2,2)数组。不过,我猜熊猫,它会填补NaN值。希望我的意思是:) –

+0

@SirajS。换句话说,它可能不会在一个周期结束时终止? –

+0

是的。元素的长度可能不能完全被列的长度整除。在这种情况下,numpy.reshape()将不起作用 –