简体   繁体   中英

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

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.

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.

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'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM