Pandas 系列仅将 NaN 填充到一定的限制

问题描述

我有一个数据集“artwork.csv” https://gitlab.com/IEA_ML_LAB/test/-/blob/80713d4823c4778d11468bcaf4a5223f6a160c88/artwork.csv

'year' 列包括 int64 和 NaN。

enter image description here

我想用文本“无日期”替换前 100 个 NaN 值。我尝试了不同的方法,但没有成功。

'year' 列有 1279 个 NaN 值。我想将 1279 个中的前 100 个设置为“无日期”

enter image description here

前 100 个 NaN 值:

enter image description here

我尝试以下命令。它们不会产生任何错误,但也不会修改系列:

df.loc[df.year.isnull(),'year'].iloc[:100] = 'no date'
(df.loc[df.year.isnull(),'year'].iloc[:100]).replace('NaN','no date',inplace=True)
(df.loc[df.year.isnull(),'year'].iloc[:100]).transform(lambda x: 'no date')

提前致谢。

解决方法

fillna 有一个 limit 参数,您可以将其设置为 100:

df['year'] = df['year'].fillna('no date',limit=100)

无需事先调用 iloc,因为这会生成额外的数据副本。

尽管小心混合字符串和浮点数在这里可能不是最佳选择,因为它在处理数据时会严重影响性能。