Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DataFrame column as list of values

I'm trying to get the columns of a pandas DataFrame as a list of values.

I can access the first column using iloc:

df.ix[:,[0]].values

However, that returns an array of lists:

>>> df3.ix[:,[1]].values
array([[  0.],
       [  0.],
       [  0.],

How can I return a list of numbers?

I can get what I want by calling the column by name and using tolist():

>>> df3['D-328'].tolist()
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 15.0,

However, when calling the column by index, that method is not available:

>>> df3.ix[:,[0]].tolist()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
    (type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'tolist'
like image 299
Charon Avatar asked Mar 02 '16 12:03

Charon


People also ask

How do you turn a column of a DataFrame into a list?

From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series. to_list() provided by the Series class to convert the series object and return a list.

How do I get a list of unique values from a column in pandas?

You can get unique values in column (multiple columns) from pandas DataFrame using unique() or Series. unique() functions. unique() from Series is used to get unique values from a single column and the other one is used to get from multiple columns.

How do I show all the values in a column in Python?

Example 1: We can have all values of a column in a list, by using the tolist() method. Syntax: Series. tolist().


1 Answers

I think you can try ix this way:

df.ix[:, 0].tolist()

And as mentioned DSM in comments, you can use iloc this way, if you need select first column by position:

df.iloc[:, 0].tolist()
like image 157
jezrael Avatar answered Oct 11 '22 12:10

jezrael