How can I find start and end occurrence of character in Python
<p>I have a dataframe <code>df</code> with the following ids (in <code>Col</code>). 
The last occurrence of A/B/C represents the start, and the last occurrence of X is the end. I should ignore any other A,B,C between start and end (e.g. rows 8 and 9).</p>

<p>I have to find start and end records from this data and assign a number to each of these occurrences. The column <code>count</code> is my desired output:</p>

<pre><code>    Col         ID
    P
    Q
    A             
    A              
    A             1
    Q             1 
    Q             1 
    B             1 
    C             1
    S             1 
    S             1
    X             1
    X             1  
    X             1 
    Q
    Q
    R
    R
    C              
    C             2 
    D             2 
    E             2 
    B             2 
    K             2 
    D             2 
    E             2 
    E             2 
    X             2 
    X             2 
</code></pre>

<p>This code: </p>

<pre><code>lc1 = df.index[df.Col.eq('A') &amp; df.Col.ne(df.Col.shift(-1))] 
</code></pre>

<p>would give me an array of all the last occurrences of Index values of 'A', in this case <code>[5]</code>.</p>

<pre><code>lc1 = df.index[df.Col.eq('C') &amp; df.Col.ne(df.Col.shift(-1))]  # [20]
lc2 = df.index[df.Col.eq('X') &amp; df.Col.ne(df.Col.shift(-1))]  # [14,29]
</code></pre>

<p>I would use <code>iloc</code> to print the count values:</p>

<pre><code>df.iloc[5:14]['count'] = 1
df.iloc[20:29]['count'] = 2
</code></pre>

<p>How can I find the indices of A/B/C together and print the count values of each start and end occurrence?</p>

<p>To find your indices of A, B, and C you can do:</p>

<pre><code>df[(df.Col =='A')|(df.Col =='B')|(df.Col =='C')].index
</code></pre>

<p>Print your start counts:</p>

<pre><code>df1 = df[df['count'] != df['count'].shift(+1)]
print df1[df1['count'] != 0]['count']
</code></pre>

<p>Print your end counts:</p>

<pre><code>df2 = df[df['count'] != df['count'].shift(-1)]
print df2[df2['count'] != 0]['count']
</code></pre>

<p>On a sidenote, calling a column <code>count</code> is a bad idea because <code>count</code> is a method of the DataFrame and then you get ambiguity when doing <code>df.count</code>.</p>

<p>EDIT: Corrected since I was answering to a wrong question.</p>

python pandas indexing shift find-occurrences