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