1

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

jpp
  • 159,742
  • 34
  • 281
  • 339
Chjul
  • 399
  • 2
  • 3
  • 10

2 Answers2

2

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
jpp
  • 159,742
  • 34
  • 281
  • 339
1

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.

Andrew F
  • 2,690
  • 1
  • 14
  • 25
  • This won't match OP's desired output, it gives `"[10, 'héllo', 'world']"` if you run `s.apply(lambda val: str(val)).iat[0]`. – jpp Nov 29 '18 at 13:29