mitsi mitsi - 4 months ago 125
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.

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

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


I use
pd.DataFrame
to convert
x


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

you should reshape your input array:

In [6]: pd.DataFrame(x.reshape(1,4), columns=nam)
Out[6]:
   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)
Out[11]:
   col1  col2  col3  col4
0     2     3     1     0