Python 将最后n行替换为NaN
我有一个数据帧Python 将最后n行替换为NaN,python,pandas,nan,Python,Pandas,Nan,我有一个数据帧df1: df1 = index col1 col2 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 例如,我想做的是将col2中的最后两行替换为NaN,因此生成的数据帧将是: index col1 col2 1 1
df1
:
df1 =
index col1 col2
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
6 6 7
例如,我想做的是将col2
中的最后两行替换为NaN,因此生成的数据帧将是:
index col1 col2
1 1 2
2 2 3
3 3 4
4 4 5
5 5 NaN
6 6 NaN
使用按位置索引,因此需要按位置索引列:
df.iloc[-2:, df.columns.get_loc('col2')] = np.nan
或与索引一起使用df.index
:
df.loc[df.index[-2:], 'col2'] = np.nan
最后,如果需要整数列:
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>
df['col2']=df['col2'].astype('Int64')
打印(df)
col1 col2
1 1 2
2 2 3
3 3 4
4 4 5
5 5
6 6
试试看:
df.col2[-2:] = np.NaN
看来《华盛顿邮报》将收集所有可能的方法
df["col2"].iloc[-2:,] = np.nan
4种方法可以做到这一点。方法3和4对我来说似乎是最好的: (一)
我认为您的解决方案未被推荐,请检查[353]中的
。这里需要DataFrame.loc
或DataFrame.iloc
谢谢@jezrael熊猫仍然允许它有什么特别的原因吗?什么时候建议使用像我这样的符号?
df["col2"].iloc[-2:,] = np.nan
df.at[5,'col2']=math.nan
df.at[6,'col2']=math.nan
df.loc[5,'col2']=np.nan
df.loc[6,'col2']=np.nan