Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Select Columns in Pandas Dataframe to Numpy Array

I would like to convert everything but the first column of a pandas dataframe into a numpy array. For some reason using the columns= parameter of DataFrame.to_matrix() is not working.

df:

  viz  a1_count  a1_mean     a1_std 0   n         3        2   0.816497 1   n         0      NaN        NaN  2   n         2       51  50.000000 

I tried X=df.as_matrix(columns=[df[1:]]) but this yields an array of all NaNs

like image 564
Adam_G Avatar asked Aug 03 '15 13:08

Adam_G


People also ask

How do I convert a column of a pandas DataFrame into a NumPy array?

You can convert select columns of a dataframe into an numpy array using the to_numpy() method by passing the column subset of the dataframe.

Can we convert DataFrame to NumPy array?

to_numpy() – Convert dataframe to Numpy array. Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of Dataframe. to_numpy() method.


1 Answers

the easy way is the "values" property df.iloc[:,1:].values

a=df.iloc[:,1:] b=df.iloc[:,1:].values  print(type(df)) print(type(a)) print(type(b)) 

so, you can get type

<class 'pandas.core.frame.DataFrame'> <class 'pandas.core.frame.DataFrame'> <class 'numpy.ndarray'> 
like image 106
176coding Avatar answered Sep 30 '22 08:09

176coding