1

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!

1
  • What do you mean each row has an item of the shape (3,5)? Can you provide the structure of the desired dataframe? Commented Jan 7, 2021 at 11:06

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.