mitsi - 1 year ago 308

Python Question

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

`x`

`nam`

`x = np.array([2,3,1,0])`

nam = ['col1', 'col2', 'col3', 'col4']

I use

`pd.DataFrame`

`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 Source

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
```