Conversion between "pandas.Series" to numpy array

Viewed 182

I have a pandas.Series that every element is a numpy.array, For example:

p = pandas.Series([numpy.array([1,2]), numpy.array([2,4])])

I try to convert the whole Series into a multi-dimensional (2,2) numpy.array, for that I use values method of Series, but this one returns a single dimension numpy array that each element in the array is a numpy.array and the dtype of the array is object:

In [18]: p = pandas.Series([numpy.array([1,2]), numpy.array([2,4])])

In [19]: p.values
Out[19]: array([array([1, 2]), array([2, 4])], dtype=object)

The result that I would like to achieve is as the series would have been created as numpy array

In [23]: a = numpy.array([numpy.array([1,2]), numpy.array([2,4])])

In [24]: a
Out[24]:
array([[1, 2],
       [2, 4]])

In [25]: a.shape
Out[25]: (2, 2)

Does anyone have an idea of how to make such a conversion? to_numpy method doesn't work also for me.

1 Answers

I would suggest following conversion:

import numpy as np
import pandas as pd

p = pd.Series([np.array([1,2]), np.array([2,4])])
np.array(p.values.tolist()).shape
Related