pd.Series of lists to numpy 2d array

Viewed 538

I have a pd.Series of lists.

i.e. df = pd.Series([['a', 'b'], ['c', 'd']])

I'd like to convert it to a 2d numpy array.

Doing this: np.array(df.values) doesn't yield the desired result, as the list is considered as an object.

How to get a 2d array?

3 Answers

In your solution only convert values to lists:

print (np.array(df.values.tolist()))
[['a' 'b']
 ['c' 'd']]

Or create DataFrame first:

print (pd.DataFrame(df.values.tolist()).values)

Just apply pd.Series:

df.apply(pd.Series).values

Okay, I just found np.stack can do that too.

df = pd.Series([['a', 'b'], ['c', 'd']])
np.stack(df.values).shape

results

(2, 2)

Related