【问题标题】:how to replace NaN value in python [duplicate]如何在python中替换NaN值[重复]
【发布时间】:2019-05-05 15:33:09
【问题描述】:

我的数据框中有一个 NaN 值列表,我想用空字符串替换 NaN 值。

到目前为止我尝试过的方法都不起作用:

df_conbid_N_1 = pd.read_csv("test-2019.csv",dtype=str, sep=';', encoding='utf-8')
df_conbid_N_1['Excep_Test'] = df_conbid_N_1['Excep_Test'].replace("NaN","")

【问题讨论】:

    标签: python pandas dataframe missing-data imputation


    【解决方案1】:

    使用fillna (docs): 一个例子-

    df = pd.DataFrame({'no': [1, 2, 3],
                        'Col1':['State','City','Town'],
                      'Col2':['abc', np.NaN, 'defg'],
                      'Col3':['Madhya Pradesh', 'VBI', 'KJI']})
    
    df
    
       no   Col1    Col2    Col3
    0   1   State   abc Madhya Pradesh
    1   2   City    NaN VBI
    2   3   Town    defg    KJI
    
    df.Col2.fillna('', inplace=True)
    df
    
        no  Col1    Col2    Col3
    0   1   State   abc     Madhya Pradesh
    1   2   City            VBI
    2   3   Town    defg    KJI
    

    【讨论】:

      【解决方案2】:

      我们有 pandas 的 fillna 来填补缺失值。


      让我们通过示例数据框了解一些用例:

      df = pd.DataFrame({'col1':['John', np.nan, 'Anne'], 'col2':[np.nan, 3, 4]})
      
         col1  col2
      0  John   NaN
      1   NaN   3.0
      2  Anne   4.0
      

      如文档中所述,fillna 接受以下内容作为填充 values

      值:标量、字典、系列或数据帧

      所以我们可以用一个常量值替换,比如一个空字符串:

      df.fillna('')
      
         col1 col2
      0  John     
      1          3
      2  Anne    4
      1
      

      您也可以替换为字典映射column_name:replace_value

      df.fillna({'col1':'Alex', 'col2':2})
      
         col1  col2
      0  John   2.0
      1  Alex   3.0
      2  Anne   4.0
      

      或者您也可以替换为另一个 pd.Seriespd.DataFrame

      df_other = pd.DataFrame({'col1':['John', 'Franc', 'Anne'], 'col2':[5, 3, 4]})
      
      df.fillna(df_other)
      
          col1  col2
      0   John   5.0
      1  Franc   3.0
      2   Anne   4.0
      

      这非常有用,因为它允许您使用从列中提取的一些统计信息来填充数据框列上的缺失值,例如 meanmode。假设我们有:

      df = pd.DataFrame(np.random.choice(np.r_[np.nan, np.arange(3)], (3,5)))
      print(df)
      
           0    1    2    3    4
      0  NaN  NaN  0.0  1.0  2.0
      1  NaN  2.0  NaN  2.0  1.0
      2  1.0  1.0  2.0  NaN  NaN
      

      那么我们就可以轻松做到了:

      df.fillna(df.mean())
      
           0    1    2    3    4
      0  1.0  1.5  0.0  1.0  2.0
      1  1.0  2.0  1.0  2.0  1.0
      2  1.0  1.0  2.0  1.5  1.5
      

      【讨论】:

        【解决方案3】:

        简单!你可以这样做

        df_conbid_N_1 = pd.read_csv("test-2019.csv",dtype=str, sep=';',encoding='utf-8').fillna("")
        

        【讨论】:

          猜你喜欢
          • 2021-09-08
          • 2021-06-27
          • 2019-04-22
          • 2019-11-08
          • 1970-01-01
          • 2018-09-24
          • 1970-01-01
          • 2014-05-22
          • 2017-08-25
          相关资源
          最近更新 更多