BobbyJohnsonOG BobbyJohnsonOG - 3 months ago 9
Python Question

Inserting a row into a pandas dataframe based on row value?

I have a DataFrame:

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


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:

B C
0 2 'a'
1 1 'b'
1 1 'c'
2 2 'a'


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

Answer

Here's one way of doing it:

duplicates = df[df['C'] == 'b'].copy()
duplicates['C'] = 'c'
df.append(duplicates).sort_index()