user1700890
user1700890

Reputation: 7730

Extract numpy arrays from pandas dataframe as matrix

I ended up with the following data structure:

import numpy as np
import pandas as pd

my_df = pd.DataFrame({'col_1': [1,2,3]})
my_df['col_1'] = my_df['col_1'].apply(lambda x: np.array([1,2,3]))
my_df.as_matrix()

it looks like this:

array([[array([1, 2, 3])],
       [array([1, 2, 3])],
       [array([1, 2, 3])]], dtype=object)

Whily I would like it to look like simply numpy matrix. Any thoughts?

Upvotes: 0

Views: 137

Answers (1)

piRSquared
piRSquared

Reputation: 294218

If you just want an array, you can

np.array(my_df.col_1.tolist())

array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

Upvotes: 2

Related Questions