Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Dataframe to 2d Array

I have a data-frame of size (140000,22) dimensions.

i have to create 2d array of equal dimensions to pass it into convolution neural network .

Can you please guide how to transform on this dataframe

like image 578
KURUVILLA ABRAHAM Avatar asked Feb 06 '19 08:02

KURUVILLA ABRAHAM


People also ask

How do you convert a DataFrame to a 2D array?

It is quite easy to transform a pandas dataframe into a numpy array. Simply using the to_numpy() function provided by Pandas will do the trick. This will return us a numpy 2D array of the same size as our dataframe (df), but with the column names discarded.

How do you convert a DataFrame to an array?

To convert Pandas DataFrame to Numpy Array, use the function DataFrame. to_numpy() . to_numpy() is applied on this DataFrame and the method returns object of type Numpy ndarray. Usually the returned ndarray is 2-dimensional.

Is a data frame a 2D array?

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.

Can we convert DataFrame to NumPy array?

Convert the DataFrame to a NumPy array. By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are float16 and float32 , the results dtype will be float32 .


2 Answers

You just need to call .values on the DataFrame.

If for example your dataframe is called df, then you can pass df.values to your convolutional neural network.

like image 82
markuscosinus Avatar answered Oct 14 '22 12:10

markuscosinus


Use arr = df.to_numpy()

See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html

It will create a 2d array where each row is the inner array.

[[row1],
 [row2],
 [row3]...
 [row n]]

To turn it into a 2d array where each column is the inner array, use transpose:

arr = np.transpose(arr)

[[all_data_in_col_1],
 [all_data_in_col_2],...
 [all_data_in_col_n]]
like image 21
Mike718 Avatar answered Oct 14 '22 14:10

Mike718