Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding rows with Nan values to Pandas DataFrame

I want to insert rows with Nan values after each row

index values
0 44
1 50
2 51
3 66
4 23

DataFrame should look like this

index values
0 44
1 Nan
2 50
3 Nan
4 51
5 Nan
6 66
7 Nan
8 23
like image 525
what's wrong CSE Avatar asked Mar 23 '26 10:03

what's wrong CSE


1 Answers

Use concat with DataFrame filled by NaNs and same indices and then use DataFrame.sort_index:

df = (pd.concat([df, pd.DataFrame(index=df.index)])
        .sort_index(kind='stable', ignore_index=True))
print (df)
   values
0    44.0
1     NaN
2    50.0
3     NaN
4    51.0
5     NaN
6    66.0
7     NaN
8    23.0
9     NaN

If need remove last missing value:

df = (pd.concat([df, pd.DataFrame(index=df.index)])
        .sort_index(kind='stable', ignore_index=True)
        .iloc[:-1])
print (df)
   values
0    44.0
1     NaN
2    50.0
3     NaN
4    51.0
5     NaN
6    66.0
7     NaN
8    23.0
like image 126
jezrael Avatar answered Mar 26 '26 01:03

jezrael



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!