Home > Software engineering >  How to reshape a pandas series after converting to numpy?
How to reshape a pandas series after converting to numpy?

Time:06-25

I have a pandas series like this:

import pandas as pd
import numpy as np

testpd = pd.Series([[[32, 43], [453, 565]], [[32, 43], [453, 565]]])

the shape of it is (2,)

I convert this into numpy array like the following

testnp = testpd.to_numpy()

the shape of the numpy array is (2,)

but ideally, it should be (2, 2, 2) or whatever the actual dimensions are, like the shape of testnps here is (2,2,2)

testnps = np.array([[[32, 43], [453, 565]], [[32, 43], [453, 565]]])

I tried to do testnp.reshape(2,2) but it gave an error "ValueError: cannot reshape array of size 2 into shape (2,2)".

How can I reshape the array to get the ideal (2,2,2) shape?

CodePudding user response:

First you can convert the pandas series into a list then cover that into numpy array. You can do

testnp = np.array(testpd.tolist())

CodePudding user response:

This should work :

testpd = pd.Series([[[32, 43], [453, 565]], [[32, 43], [453, 565]]])
testnp = testpd.to_numpy()
testnp = testnp.tolist()
testnp = np.asarray(testnp)
testnp.shape

Output : (2,2,2)

CodePudding user response:

This works to:

out = np.stack(testpd)
print(out.shape)
  • Related