将熊猫数据框从(12,1)重塑为特定形状(3,4)

时间:2019-05-02 20:49:20

标签: pandas dataframe

我要完成一个特定的重塑。我看不到如何使用np.reshape或pd.pivot使它正常工作。任何帮助将不胜感激。

df = [1,2,3,4,1,2,3,4,1,2,3,4]

#I would like the output to look like:

0  1  2  3
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4

1 个答案:

答案 0 :(得分:1)

pandas.DataFrame.valuespandas.DataFrame.to_numpynumpy.reshape一起使用

  

每个熊猫的文档:建议使用DataFrame.to_numpy()

import numpy as np 
import pandas as pd 

import pandas as pd 

list = [1,2,3,4,1,2,3,4,1,2,3,4]
df = pd.Series(list)

# Option1 using 'values' with reshape()
print('Option1 : \n', df.values.reshape(3,4).T)

# Option2 using 'to_numpy()' with reshape()
print('Option2 : \n',df.to_numpy().reshape(3,4).T)

# Get reshape dataframe to vector
df1 = pd.DataFrame(df.to_numpy().reshape(3,4).T)

# dataframe to vector Option1 
print('Option1: Convert dataframe to vector: \n', np.reshape(df1.values.T, (1, df1.size)))

# dataframe to Option2
print('Option2: Convert dataframe to vector: \n', df1.to_numpy().T.reshape(1, df1.size))

# numpy array to vector :
df2 = df.to_numpy().reshape(3,4).T

print('Array to vector: \n', np.reshape(df2.T, (1, df2.size)))
Out:
Option1 :
 [[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]]
Option2 :
 [[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]]
Option1: Convert dataframe to vector:
 [[1 2 3 4 1 2 3 4 1 2 3 4]]
Option2: Convert dataframe to vector:
 [[1 2 3 4 1 2 3 4 1 2 3 4]]
Array to vector:
 [[1 2 3 4 1 2 3 4 1 2 3 4]]

See here interactive