Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace n last rows with NaN

Tags:

python

pandas

nan

I have a data frame df1:

df1 =

index     col1     col2
1         1        2
2         2        3
3         3        4
4         4        5
5         5        6
6         6        7

What I would like to do is for example to replace the last two rows in col2 with NaN, so the resulting data frame would be:

index     col1     col2
1         1        2
2         2        3
3         3        4
4         4        5
5         5        NaN
6         6        NaN
like image 557
Denver Dang Avatar asked Apr 23 '26 18:04

Denver Dang


2 Answers

Use indexing by positions with DataFrame.iloc, so need position by Index.get_loc for column:

df.iloc[-2:, df.columns.get_loc('col2')] = np.nan

Or use DataFrame.loc with indexing df.index:

df.loc[df.index[-2:], 'col2'] = np.nan

print (df)
   col1  col2
1     1   2.0
2     2   3.0
3     3   4.0
4     4   5.0
5     5   NaN
6     6   NaN

Last if need integer column:

df['col2'] = df['col2'].astype('Int64')
print (df)
   col1  col2
1     1     2
2     2     3
3     3     4
4     4     5
5     5  <NA>
6     6  <NA>
like image 167
jezrael Avatar answered Apr 25 '26 09:04

jezrael


Just try:

df.col2[-2:] = np.NaN
like image 45
sharathnatraj Avatar answered Apr 25 '26 10:04

sharathnatraj



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!