Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of vertical bars | in pandas string has strange behaviour?

Tags:

python

pandas

I want to count the number of instances of vertical bars "|" in a each row of a particular column in a pandas dataframe. But using str.count("|") yields some strange behaviour:

import pandas as pd
df = pd.DataFrame(['some text', None, 'a|few|vertical|bars', 'one|'])
df[0].str.count("|")

outputs

0    10.0
1     NaN
2    20.0
3     5.0
Name: 0, dtype: float64

What's going on here? If I use apply instead, I get the expected answer:

df.apply(lambda x: str(x[0]).count("|"),axis=1)

yields

0    0
1    0
2    3
3    1
dtype: int64
like image 680
Luftbahnfahrer Avatar asked Jan 25 '26 14:01

Luftbahnfahrer


1 Answers

Try this, pat is a regex string and | is a regex operator, OR, so escape with '\', blackslash:

df[0].str.count('\|')

Output:

0    0.0
1    NaN
2    3.0
3    1.0
Name: 0, dtype: float64

Note: str.count in the standard library is different from pd.Series.str.count where the former doesn't use regex, but the method from pandas does per docs linked above.

like image 64
Scott Boston Avatar answered Jan 28 '26 02:01

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!