Replace n last rows with NaN

Viewed 161

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
4 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>

It seems like the post is going to gather all the possible ways

df["col2"].iloc[-2:,] = np.nan

4 ways to do this. Ways 3 and 4 seem the best to me:

1)

df.at[5,'col2']=math.nan
df.at[6,'col2']=math.nan
df.loc[5,'col2']=np.nan 
df.loc[6,'col2']=np.nan
  1. from the answer above

    df.col2[-2:]=np.nan

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

Related