mitsi
mitsi

Reputation: 1165

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

Upvotes: 3

Views: 191

Answers (2)

jezrael
jezrael

Reputation: 863301

Another simplier solution with []:

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

print (pd.DataFrame([x], columns=nam))
   col1  col2  col3  col4
0     2     3     1     0

Upvotes: 7

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210932

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

Upvotes: 4

Related Questions