mitsi mitsi - 6 months ago 173
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


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