Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将最后n行替换为NaN_Python_Pandas_Nan - Fatal编程技术网

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对我来说似乎是最好的:

(一)

  • 从上面的答案来看

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

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


  • 我认为您的解决方案未被推荐,请检查[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