3

I have a DataFrame with shape: 720*720 2D. I wanna convert it to 1D dimension without changing its values. How can I do this using Pandas?

Kaveh P. Yousefi
  • 165
  • 1
  • 2
  • 13

1 Answers1

5

Use numpy.ravel with converted DataFrame to numpy array:

np.random.seed(123)
df = pd.DataFrame(np.random.randint(10, size=(3,3)))
print (df)
   0  1  2
0  2  2  6
1  1  3  9
2  6  1  0

out = df.values.ravel('F')
#alternative for pandas 0.24+
#out = df.to_numpy().ravel('F')
print (out)
[2 1 6 2 3 1 6 9 0]

s = pd.Series(df.values.ravel('F'))
#alternative for pandas 0.24+
#s = pd.Series(df.to_numpy().ravel('F'))
print (s)
0    2
1    1
2    6
3    2
4    3
5    1
6    6
7    9
8    0
dtype: int32
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252