Count the number of occurrences of two characters in python column
<p>I have a dataframe (df) with variable Area representing the Area code. I need to find the number of occurences for Z followed by X
In the following example Z->X is repeated twice which means count is 2</p>

<pre><code>Area
Z
A
B
Z
X
A
B
Z
X
</code></pre>

<p>I have tried the following to find True/False</p>

<pre><code>    df.Area.str.contains(r'Z|X')
</code></pre>

<p>I am sure that this is wrong approach as it didn't give me a desired result. Any other way of doing it?</p>

<p>You need the <code>shift()</code> function, specify the <code>period</code> parameter to be <code>-1</code> to shift the series one step forward, and this guarantees that <code>Z</code> is followed by <code>X</code>:</p>

<pre><code>((df.Area == "Z") &amp; (df.Area.shift(-1) == "X")).sum()
# 2
</code></pre>

<p>A closer look at how <code>shift</code> works:</p>

<pre><code>df["Area_shift"] = df.Area.shift(-1)

df
#  Area  Area_shift
# 0   Z           A
# 1   A           B
# 2   B           Z
# 3   Z           X
# 4   X           A
# 5   A           B
# 6   B           Z
# 7   Z           X
# 8   X         NaN
</code></pre>

python string find-occurrences