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.
concat() function to insert a row at any given position in the dataframe.
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.
Here's one way of doing it:
duplicates = df[df['C'] == 'b'].copy()
duplicates['C'] = 'c'
df.append(duplicates).sort_index()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With