Convert pandas dataframe of lists into numpy array

Viewed 706

I have the following dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame([{'a': [1,3,2]},{'a': [7,6,5]},{'a': [9,8,8]}])
df

df['a'].to_numpy()
df['a'].to_numpy()

=> array([list([1, 3, 2]), list([7, 6, 5]), list([9, 8, 8])], dtype=object)

How can I get a numpy array of shape (3,3) without writing a for loop?

2 Answers

First create nested lists and then convert to array, only necessary all lists with same lengths:

arr = np.array(df.a.tolist())
print (arr)
[[1 3 2]
 [7 6 5]
 [9 8 8]]

If always have the same length

pd.DataFrame(df.a.tolist()).values
array([[1, 3, 2],
       [7, 6, 5],
       [9, 8, 8]])
Related