Vance Pyton
Vance Pyton

Reputation: 174

How to reshape a pandas series after converting to numpy?

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?

Upvotes: 2

Views: 196

Answers (3)

lmielke
lmielke

Reputation: 125

This works to:

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

Upvotes: 0

Gravity Mass
Gravity Mass

Reputation: 605

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

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

Upvotes: 2

FlippingTook
FlippingTook

Reputation: 161

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)

Upvotes: 0

Related Questions