Convert Numpy Array to Pandas DataFrame Columns (as a Single Row)

I have a numpy array that looks like this:

a = np.array([35,2,160,56,120,80,1,1,0,0,1]) 

Then I try to convert this array to a pandas dataframe with the logic "one column value-one" as follows:

 columns=['age','gender','height', 'weight','ap_hi','ap_lo', 'cholesterol','gluc','smoke', 'alco','active'] values = a df = pd.DataFrame(a,columns=columns) 

This approach raises a ValueError: The form of the passed values ​​(1, 11), indexes imply (11, 11). What am I doing wrong and how to do it right?

Thanks!

+5
source share
2 answers

You need numpy.reshape :

 columns=['age','gender','height', 'weight','ap_hi','ap_lo', 'cholesterol','gluc','smoke', 'alco','active'] a = np.array([35,2,160,56,120,80,1,1,0,0,1]) df = pd.DataFrame(a.reshape(-1, len(a)),columns=columns) print (df) age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \ 0 35 2 160 56 120 80 1 1 0 0 active 0 1 

If the change operation is fuzzy to read, a more explicit way to add the dimension to the 1d array is to use numpy.atleast_2d

 pd.DataFrame(np.atleast_2d(a), columns=columns) 

Or it’s easier to add [] (but slower if there are really many columns):

 df = pd.DataFrame([a],columns=columns) print (df) age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \ 0 35 2 160 56 120 80 1 1 0 0 active 0 1 

Thanks to Divakar for the suggestion :

 df = pd.DataFrame(a[None],columns=columns) print (df) age gender height weight ap_hi ap_lo cholesterol gluc smoke alco \ 0 35 2 160 56 120 80 1 1 0 0 active 0 1 

And one more solution, thanks piRSquared :

 pd.DataFrame([a], [0], columns) 
+7
source

Just change the array to what you need for the data frame.

 import pandas as pd import numpy as np a = np.array([35,2,160,56,120,80,1,1,0,0,1]) columns=['age','gender','height', 'weight','ap_hi','ap_lo', 'cholesterol','gluc','smoke', 'alco','active'] df = pd.DataFrame(np.reshape(a, (1,len(a))),columns=columns) 
0
source

Source: https://habr.com/ru/post/1270215/


All Articles