nunodsousa
nunodsousa

Reputation: 2785

Conversion of a numpy matrix into a single column pandas

Let us consider a matrix with shape 3x3 written as a numpy array:

np.array([[1,2,3],[4,5,6],[7,8,9]])

The goal is to store the previous vectors in a pandas dataframe with a single column. In the following image is a representation of the objective.

enter image description here

Upvotes: 2

Views: 3669

Answers (2)

piRSquared
piRSquared

Reputation: 294328

Use tolist on the array as the value in a dictionary.

pd.DataFrame({0: np.array([[1,2,3],[4,5,6],[7,8,9]]).tolist()})

           0
0  [1, 2, 3]
1  [4, 5, 6]
2  [7, 8, 9]

Or without the dictionary

pd.DataFrame(np.array([[1,2,3],[4,5,6],[7,8,9]])[:, None].tolist())

           0
0  [1, 2, 3]
1  [4, 5, 6]
2  [7, 8, 9]

Upvotes: 3

Marc Frame
Marc Frame

Reputation: 1001

pd.DataFrame([[i] for i in np.array([[1,2,3],[4,5,6],[7,8,9]])])

Upvotes: 3

Related Questions