mitsi mitsi - 1 year ago 486
Python Question

What index should I use to convert a numpy array into a pandas dataframe?

I am trying to convert a simple numpy array into a pandas dataframe.

is my array,
is the list of the columns names.

x = np.array([2,3,1,0])
nam = ['col1', 'col2', 'col3', 'col4']

I use
to convert

y = pd.DataFrame(x, index=(1:4) , columns=nam)

But I have this error message :

ValueError: Shape of passed values is (1, 4), indices imply (4, 4)

I tried to adjust the index parameter but I can't find the solution.

I want my dataframe to look like this :

col1 col2 col3 col4

2 3 1 0

Answer Source

you should reshape your input array:

In [6]: pd.DataFrame(x.reshape(1,4), columns=nam)
   col1  col2  col3  col4
0     2     3     1     0

or bit more flexible:

In [11]: pd.DataFrame(x.reshape(len(x) // len(nam), len(nam)), columns=nam)
   col1  col2  col3  col4
0     2     3     1     0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download