Convert data to list

I have a pandas dataframe, which I convert to a numpy array as follows:

df.values 

which gives the following result:

 array([[2], [0], [1], ..., [0], [1], [0]], dtype=int64) 

However, I want to get the list as follows:

 [0, 2, 3] 

Any idea how to do this?

+6
source share
2 answers

Maybe you can use iloc or loc to select a column and then tolist :

 print df a 0 2 1 0 2 1 3 0 4 1 5 0 print df.values [[2] [0] [1] [0] [1] [0]] print df.iloc[:, 0].tolist() [2, 0, 1, 0, 1, 0] 

Or maybe:

 print df.values.tolist() [[2L], [0L], [1L], [0L], [1L], [0L]] print df.iloc[:, 0].values.tolist() [2L, 0L, 1L, 0L, 1L, 0L] print df.loc[:, 'a'].tolist() [2, 0, 1, 0, 1, 0] print df['a'].tolist() [2, 0, 1, 0, 1, 0] 

But maybe you need flatten :

 print df.values.flatten() [2 0 1 0 1 0] print df.iloc[:, 0].values.flatten() [2 0 1 0 1 0] 
+6
source

It looks like you have a dataframe with one column and multiple rows. Remember that this is a two-dimensional array, you must slice the first column, and then list the values ​​inside this column.

This should do it:

 df[0].values.tolist() 

df[0] - selects all values ​​in the first column. For the second column, you should use df[1] third df[2] , etc.

You can determine the shape of your data frame by running df.shape . This will show you how many rows and columns exist in your data framework, for example. (9,1) , which means 9 rows and 1 column

+1
source

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


All Articles