I would like to convert my series into strings :
s = pd.Series({'A':[10,'héllo','world']})
to something like this
s = pd.Series({'A':['10','héllo','world']})
But whithout using iteration. I tried to used pandas.DataFrame.astype but it didn't seem to work.
Thanks a lot for your help
The problem is you've defined a series of lists :
s = pd.Series({'A':[10,'héllo','world']})
print(s)
A [10, héllo, world]
dtype: object
If this is truly what you have, you need to modify each list in a Python-level loop. For example, via pd.Series.apply
:
s = s.apply(lambda x: list(map(str, x)))
If you have a series of scalars , then astype
will work:
s = pd.Series([10,'héllo','world'])
res = s.astype(str)
print(res, res.map(type), sep='\n'*2)
0 10
1 héllo
2 world
dtype: object
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
dtype: object
You could do
string_series = s.apply(lambda val: str(val))
but that is iterating in the background.
You should note that
s.astype(str)
does not operate in place but returns a copy.
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.