Stark
Stark

Reputation: 197

How to convert ndarray to a pandas DataFrame |python|pandas|numpy|

I'm trying to convert my numpy array into a dataframe,

array:

array([[[9.447859e+06, 3.000000e+00, 1.350000e+01, 7.000000e+00]]

   [[9.447859e+06, 2.000000e+00, 1.350000e+01, 4.000000e+00]],

   [[9.447859e+06, 1.000000e+00, 1.350000e+01, 7.000000e+00]]])

expected output:

A            B            C            D
9.447859e+06 3.000000e+00 1.350000e+01 7.000000e+00
9.447859e+06 2.000000e+00 1.350000e+01 4.000000e+00
9.447859e+06 1.000000e+00 1.350000e+01 7.000000e+00

can I get a solution for this? Thanks.

Upvotes: 0

Views: 4300

Answers (4)

John Mommers
John Mommers

Reputation: 140

This works (after removing the double brackets):

import pandas as pd
import numpy as np
a = np.array([[9.447859e+06, 3.000000e+00, 1.350000e+01, 7.000000e+00],

   [9.447859e+06, 2.000000e+00, 1.350000e+01, 4.000000e+00],

   [9.447859e+06, 1.000000e+00, 1.350000e+01, 7.000000e+00]])

b = pd.DataFrame(data=a )
b

Upvotes: 0

Andreas
Andreas

Reputation: 9207

You can specify which part of the array to use as data:

pd.DataFrame(data=a[:,0], index=range(0, len(a)), columns=['A', 'B', 'C', 'D'])

Upvotes: 0

Rishin Rahim
Rishin Rahim

Reputation: 655

Try this

import numpy as np
a = np.array([[[1, 2,3, 4]], [[5, 6, 7, 8]]])

m,n,r = a.shape
out_arr = a.reshape(m*n,-1)
out_df = pd.DataFrame(out_arr,columns =['A','B','C','D'])
out_df

Result

    A   B   C   D
0   1   2   3   4
1   5   6   7   8

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

You can use numpy.squeeze() to remove axes of length one from array.

df = pd.DataFrame(np.squeeze(data), columns=['A', 'B', 'C', 'D'])

Upvotes: 3

Related Questions