How to convert the column values of pandas series to list in Python?

Viewed 347

I have a pandas series which after printing looks like -

0        NaN
1     20.307
2    -16.879
3      4.598
4     21.978
5    -12.913
dtype: float64

I would like to convert the values in the second column to a list such that it looks like -

[0, 20.307, -16.879, 4.598, 21.978, -12.913]

I tried doing - my_series.iloc[:, 1] but i am getting the error - pandas.core.indexing.IndexingError: Too many indexers Can someone help? Thanks.

4 Answers

If use iloc[:, 1] it want select second column, but in Series is no columns, so raise error.

If want select all values without first use indexing [1:]:

L = my_series.iloc[1:].tolist()

Or remove missing values by Series.dropna:

L = my_series.dropna().tolist()

Or replace NaN to 0 by Series.fillna:

L = my_series.fillna(0).tolist()

You can use Series.fillna():

In [2640]: my_series.fillna(0).tolist()
Out[2640]: [0.0, 20.307, -16.879, 4.598, 21.978, -12.913]

Lets try

list(df.my_series.fillna(0))

As I see from your expected result, you don't want to just drop NaN elements but rather to convert them to 0.

So to get your desired result, run:

result = my_series.fillna(0).tolist()
Related