Finding the occurrence and position of a character in python
<p>I have a variable (var) with ids
I am interested in finding out the position of last occurrence of Z</p>

<p>I have tried to convert it to an array with their positions</p>

<pre><code>    zf1=np.where(df2['Var']=="Z")
</code></pre>

<p>This will give me the result as    </p>

<pre><code>    (array([4,5,6,7,8,9,10,11,12,22,23,24,25],dtype=int64),)
</code></pre>

<p>My idea was to find the difference of these values and look for -1 - I use the index value of this -1 to add an id next to it</p>

<pre><code>    np.diff(zf1)


    Var              ID
    A
    B
    C
    Z
    Z
    Z
    Z
    Z
    Z
    Z
    Z
    Z          1
    X
    X
    X
    X
    X
    X
    B
    A
    C
    Z
    Z
    Z
    Z           2
</code></pre>

<p>np.diff is not giving me -1. Is there any alternate method? </p>

<p><strong><em>Get Index values</em></strong></p>

<pre><code>df2.index[df2.Var.eq('Z') &amp; df2.Var.ne(df2.Var.shift(-1))]
</code></pre>

<p><strong><em>Filter <code>df2</code></em></strong></p>

<pre><code>df2[df2.Var.eq('Z') &amp; df2.Var.ne(df2.Var.shift(-1))]
</code></pre>

python pandas position np find-occurrences