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
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>
Just try:
df.col2[-2:] = np.NaN
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