Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an empty row before a definite row in Python DataFrame?

I'm working with a huge dataframe in python and sometimes I need to add an empty row or several rows in a definite position to dataframe. For this question I created a small dataframe df in order to show, what I want to achieve.

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

If a row value is 27000, I want to add an empty row before it. I can insert row after with Concat but I can't really think of a way of adding it before..

like image 366
Tef Don Avatar asked Oct 30 '25 19:10

Tef Don


1 Answers

You can create a helper cumsum column for groupby then append a blank row only for the first group and then concat:

out = pd.concat((g.append(pd.Series(),ignore_index=True) if i==0 else g 
       for i, g in df.groupby(df['Price'].eq(27000).cumsum())))

print(out)

            Brand    Price
0     Honda Civic  22000.0
1  Toyota Corolla  25000.0
2             NaN      NaN
2      Ford Focus  27000.0
3         Audi A4  35000.0
like image 92
anky Avatar answered Nov 02 '25 09:11

anky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!