【问题标题】:How useful it is to convert nan to NaN?将 nan 转换为 NaN 有多大用处?
【发布时间】:2019-12-26 07:21:24
【问题描述】:

我正在尝试运行已经由其他人编写的代码。但是,我不确定将nan 转换为NaN 需要什么

关于这个问题的一段代码

obs['valuestring'].astype(str).str.strip().mask(obs['valuestring'].isna())

上面的代码给出了这样的输出

但我觉得下面这段代码应该没问题。不是吗?

obs['valuestring'].astype(str).str.strip()

它产生与上面相同的输出,但nan而不是NaN

我知道np.nannp.NaN,所以尝试了解这有什么有用的,我错过了吗?

您能否帮助我了解将nan 转换为NaN 的必要性以及我应该何时进行此类转换?

【问题讨论】:

    标签: python python-3.x pandas dataframe nan


    【解决方案1】:

    这是不同的,因为第二个没有缺失值,而是NaN的字符串表示 - 字符串nan

    obs = pd.DataFrame({'valuestring':['a ', np.nan, np.nan]})
    print (obs)
      valuestring
    0          a 
    1         NaN
    2         NaN
    
    s = obs['valuestring'].astype(str).str.strip().mask(obs['valuestring'].isna())
    print (s)
    0      a
    1    NaN
    2    NaN
    Name: valuestring, dtype: object
    
    print (s.isna())
    0    False
    1     True
    2     True
    Name: valuestring, dtype: bool
    

    s = obs['valuestring'].astype(str).str.strip()
    print (s)
    0      a
    1    nan
    2    nan
    Name: valuestring, dtype: object
    
    print (s.isna())
    0    False
    1    False
    2    False
    Name: valuestring, dtype: bool
    
    print (s.eq('nan'))
    0    False
    1     True
    2     True
    Name: valuestring, dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 2017-06-18
      • 2016-03-12
      • 2011-07-04
      • 2021-12-23
      • 2020-10-24
      • 2012-01-01
      • 2014-06-20
      • 2020-01-23
      相关资源
      最近更新 更多