Inserting a row into a pandas dataframe based on row value?
<p>I have a DataFrame:</p>

<pre><code>df = pd.DataFrame({'B':[2,1,2],'C':['a','b','a']})
  B C
0 2 'a'
1 1 'b'
2 2 'a'
</code></pre>

<p>I want to insert a row above any occurrence of 'b', that is a duplicate of that row but with 'b' changed to 'c', so I end up with this:</p>

<pre><code>  B C
0 2 'a'
1 1 'b'
1 1 'c'
2 2 'a'
</code></pre>

<p>For the life of me, I can't figure out how to do this.</p>

<p>Here's one way of doing it:</p>

<pre><code>duplicates = df[df['C'] == 'b'].copy()
duplicates['C'] = 'c'
df.append(duplicates).sort_index()
</code></pre>

python pandas numpy dataframe insert