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'
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.
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.
Example 1: We can have all values of a column in a list, by using the tolist() method. Syntax: Series. tolist().
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With