根据索引从一列 pandas 数据框转换为 3 列

convert from one column pandas dataframe to 3 columns based on index

我有:

    col1
0   1
1   2
2   3
3   4
4   5
5   6
...

我希望原始数据帧的每 3 行成为新数据帧中的一行:

    col1    col2    col3
0   1       2       3
1   4       5       6
...

有什么建议吗?

您可以使用 set_indexunstack 获得正确的形状,并使用 add_preffix 更改列名称:

print (df.set_index([df.index//3, df.index%3+1])['col1'].unstack().add_prefix('col'))
   col1  col2  col3
0     1     2     3
1     4     5     6

如果原始索引不是连续值,但您仍想每 3 行重塑一次,请将 df.index 替换为 np.arange(len(df)),以便在 set_index

dataframe 的值是一个数组,可以使用 numpy 的 reshape 方法对其进行整形。然后,使用重塑后的值创建一个新的数据框。假设您现有的数据框是 df-

df_2 = pd.DataFrame(df.values.reshape(2, 3), columns=['col1', 'col2', 'col3'])

这将创建两行三列的新数据框。

   col1   col2  col3
0   0      1      2
1   3      4      5

您可以转换 numpy 数组中的列,然后重新整形。

In [27]: np.array(df['col1']).reshape( len(df) // 3 , 3 )
Out[27]:
array([[1, 2, 3],
       [4, 5, 6]])

In [..] :reshaped_cols = np.array(df['col1']).reshape( len(df) // 3 , 3 )


pd.DataFrame( data = reshaped_cols , columns = ['col1' , 'col2' , 'col3' ] )


Out[30]:
   col1  col2  col3
0     1     2     3
1     4     5     6