Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas Series str replace not working when chained together

I discovered some tricky handling of Series with chained string operations.

I eventually figured out that each string operation has too prefixed with '.str'. Would be nice if chained operations could be performed similiar to an apply.

Here is the code

# Create dataframe
d = dict(a = ['ab\ncdef'], b = ['bbccdd'])
p = pd.DataFrame.from_dict(d)
print(p)

x1 = p.a.str.replace('c','=').replace('\n','-')[0]
x2 = p.a[0].replace('c','=').replace('\n','-')
x3 = p.apply(lambda r : r.a.replace('c','=').replace('\n','-'),axis=1)[0]
x4 = p.a.str.replace('c','=').str.replace('\n','-')[0]
x1,x2,x3,x4

Here is the output. You can see that x1 does not work but x4 works

      a       b
0  ab\ncdef  bbccdd

('ab\n=def', 'ab-=def', 'ab-=def', 'ab-=def')

As x3,x4 are solutions... I am posting this mainly to share and ask if chained string operations should be applied on a single Series? Just curious if others have hit this.

like image 875
frankr6591 Avatar asked Sep 08 '25 10:09

frankr6591


1 Answers

do it this way:

In [89]: p.a
Out[89]:
0    ab\ncdef
Name: a, dtype: object

In [90]: p.a.str.replace('c','=').str.replace('\n','-')
Out[90]:
0    ab-=def
Name: a, dtype: object

PS pay attention at the second .str

In [91]: p.a.str.replace('c','=').replace('\n','-')
Out[91]:
0    ab\n=def
Name: a, dtype: object
like image 193
MaxU - stop WAR against UA Avatar answered Sep 10 '25 02:09

MaxU - stop WAR against UA