Andreyn
Andreyn

Reputation: 314

Convert 3d numpy array to 1 column pandas df with 2d arrays

I would Convert 3d numpy array to a pandas dataframe that has 1 column, made out of 2d numpy arrays.

concrete example:

np_array = np.zeros((10,3,5))
print(np_array.shape) # (10, 3, 5)

so from this numpy array I would like to create a dataframe with 1 column, that has 10 rows, each row has an item of the shape (3,5).

trying to convert it as-is to pd.DataFrame(np_array) throws out ValueError: Must pass 2-d input error.

Thanks!

Upvotes: 1

Views: 805

Answers (2)

Noah Smith
Noah Smith

Reputation: 78

Perhaps a list comprehension?

import numpy as np
import pandas as pd
np_array = np.zeros((10,3,5))    
pd.DataFrame(data = [[x] for x in np_array])

Upvotes: 2

adir abargil
adir abargil

Reputation: 5745

you can do this ,initialize the data frame with a dict to decalre what exactly is a columns, and turn the top level of the np.array to list (it turns it to list of 2d arrays):

>>>pd.DataFrame(dict(rows = list(np_array)))
    rows
0   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
1   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
2   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
3   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
4   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
5   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
6   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
7   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
8   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....
9   [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0....

Upvotes: 1

Related Questions