Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 631
BobbyJohnsonOG Avatar asked Aug 31 '16 17:08

BobbyJohnsonOG


People also ask

How do I add a row to a panda in a specific position?

concat() function to insert a row at any given position in the dataframe.

How do I add a row number to a DataFrame in pandas?

We can also add multiple rows using the pandas. concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.


1 Answers

Here's one way of doing it:

duplicates = df[df['C'] == 'b'].copy()
duplicates['C'] = 'c'
df.append(duplicates).sort_index()
like image 113
Ciarán Tobin Avatar answered Oct 27 '22 00:10

Ciarán Tobin