【问题标题】:Replace numerical values with NaN in Python在 Python 中用 NaN 替换数值
【发布时间】:2019-11-08 15:31:22
【问题描述】:

我想用 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

但返回:

AttributeError: 'Series' 对象没有属性 'istype'

有什么建议吗?

谢谢

【问题讨论】:

标签: python pandas replace nan


【解决方案1】:

您可以使用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

【讨论】:

  • 当你使用像122.168.0.34这样的IP地址时它会失败
  • @MEdwin 第一个解决方案不会。此外,考虑到这个问题,IP 地址是一个相当大的飞跃。
  • 真的。第一个是实心的。
  • 感谢您的帮助!完美运行
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 2019-05-05
  • 2021-09-16
相关资源
最近更新 更多