在 Python 中用 NaN 替换数值

Replace numerical values with NaN in Python

我想用 NaN 替换 DataFrame 列中的所有数值

输入

A       B       C
test    foo     xyz
hit     bar     10
hit     fish    90
hit     NaN     abc
test    val     20
test    val     90

期望的输出:

A       B       C
test    foo     xyz
hit     bar     NaN
hit     fish    NaN
hit     NaN     abc
test    val     NaN
test    val     NaN

我尝试了以下方法:

db_old.loc[db_old['Current Value'].istype(float), db_old['Current Value']] = np.nan

但 returns:

AttributeError: 'Series' object has no attribute 'istype'

有什么建议吗?

谢谢

您可以使用 to_numeric:

屏蔽数值
df['C'] = df['C'].mask(pd.to_numeric(df['C'], errors='coerce').notna())
df
      A     B    C
0  test   foo  xyz
1   hit   bar  NaN
2   hit  fish  NaN
3   hit   NaN  abc
4  test   val  NaN
5  test   val  NaN

to_numeric 是最通用的解决方案,无论您有一列字符串还是混合对象,它都应该有效。


如果它是一列字符串,而您只想保留字母字符串,str.isalpha 可能就足够了:

df['C'] = df['C'].where(df['C'].str.isalpha())
df
      A     B    C
0  test   foo  xyz
1   hit   bar  NaN
2   hit  fish  NaN
3   hit   NaN  abc
4  test   val  NaN
5  test   val  NaN

虽然这专门保留了没有数字的字符串。


如果你有一列混合对象,这里还有另一个解决方案,使用 str.match(任何带有 na 标志的 str 方法,真的)和 na=False:

df['C'] = ['xyz', 10, 90, 'abc', 20, 90]

df['C'] = df['C'].where(df['C'].str.match(r'\D+$', na=False))
df
      A     B    C
0  test   foo  xyz
1   hit   bar  NaN
2   hit  fish  NaN
3   hit   NaN  abc
4  test   val  NaN
5  test   val  NaN