Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform pandas.core.series.Series to list?

Tags:

python

pandas

I tried

print(type(numbers[2]))
numbers[2].tolist()
print(type(numbers[2]))

that doesn't work. I got

<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>

Numbers is a matrix.

like image 442
Lukáš Altman Avatar asked Mar 28 '19 19:03

Lukáš Altman


People also ask

How do I change the series type in pandas?

Change data type of a series in PandasUse a numpy. dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy. dtype or Python type to cast one or more of the DataFrame's columns to column-specific types.

Is a pandas series the same as a list?

Pandas series is a 1-dimensional list of values ( can be of mixed data types — integer, float, text) stored with a labeled index.

How do you convert a number to a series list in Python?

tolist() method is used to convert a Series to a list in Python. In case you need a Series object as a return type use series() function to easily convert the list, tuple, and dictionary into a Series.


2 Answers

The .tolist() call will not update your structure in-place. Instead the method will return a new list, without modifying the original pd.Series object.

That means we must assign the result to the original variable to update it. However, if the original variable is a slice of a pd.DataFrame() we cannot do this, since the DataFrame will automatically convert a list to a pd.Series when assigning.

That means, doing numbers[2] = numbers[2].tolist() will still have numbers[2] being a pd.Series. To actually get a list, we need to assign the output to another (perhaps new) variable, that is not part of a DataFrame.

Thus, doing

numbers_list = numbers[2].tolist()
print(type(numbers_list))

will output <class 'list'> as expected.

like image 59
JohanL Avatar answered Oct 16 '22 14:10

JohanL


This doesn't change anything in place since you are not assigning it:

print(type(numbers[2]))
numbers[2].tolist()
print(type(numbers[2]))

should be changed to:

print(type(numbers[2]))
numbers2list = numbers[2].tolist()
print(type(numbers2list))

returns:

<class 'pandas.core.series.Series'>
<class 'list'>
like image 45
d_kennetz Avatar answered Oct 16 '22 13:10

d_kennetz