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.
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.
Pandas series is a 1-dimensional list of values ( can be of mixed data types — integer, float, text) stored with a labeled index.
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.
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'>
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