【问题标题】:How to replace specific character in pandas column with null?如何用 null 替换 pandas 列中的特定字符?
【发布时间】:2018-10-04 09:50:48
【问题描述】:

我在数据集中有一列,关于分类公司规模,目前看起来像 this,其中“-”连字符当前表示缺失数据:

我想用空值更改缺失值中的“-”,以便分析缺失数据。但是,当我使用带有 None 值的 pd 替换工具(参见下面的代码)时,它似乎也会生成任何真正的条目,因为它们还包含连字符(例如 51-200)。

df['Company Size'].replace({'-': None},inplace =True, regex= True)

我怎样才能只替换单独的连字符而保持其他条目不变?

【问题讨论】:

  • 不要使用regex = True。那是子字符串

标签: python database pandas replace


【解决方案1】:

您无需使用 regex=True。

df['Company Size'].replace({'-': None},inplace =True)

【讨论】:

  • 谢谢!完美运行。
  • 补充一点:我刚刚浪费了很多时间才发现 None 在字典之外似乎不起作用。使用 pandas 0.23.4,.replace(to_replace='#####', value=None) 不起作用,但 .replace({'#####': None}) 起作用。
【解决方案2】:

你也可以这样做:

df['column_name'] = df['column_name'].replace('-','None')

【讨论】:

    【解决方案3】:
    import numpy as np
    
    df.replace('-', np.NaN, inplace=True)
    

    这段代码对我有用。

    【讨论】:

      【解决方案4】:

      你可以这样做

      import numpy as np
      import pandas as pd
      
      
      df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                         'B': [5, 6, 7, 8, 9],
                         'C': ['a', '-', 'c--', 'd', 'e']})
      
      df['C'] = df['C'].replace('-', np.nan)
      df = df.where((pd.notnull(df)), None) 
      # can also use this -> df['C'] = df['C'].where((pd.notnull(df)), None)
      
      print(df)
      

      输出:

         A  B     C
      0  0  5     a
      1  1  6  None
      2  2  7   c--
      3  3  8     d
      4  4  9     e
      

      另一个例子:

      df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                         'B': ['5-5', '-', 7, 8, 9],
                         'C': ['a', 'b', 'c--', 'd', 'e']})
      
      df['B'] = df['B'].replace('-', np.nan)
      df = df.where((pd.notnull(df)), None)
      print(df)
      

      输出:

         A     B    C
      0  0   5-5    a
      1  1  None    b
      2  2     7  c--
      3  3     8    d
      4  4     9    e
      

      【讨论】:

        猜你喜欢
        • 2018-12-20
        • 1970-01-01
        • 2023-04-04
        • 2021-07-12
        • 2020-01-31
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 2021-09-12
        相关资源
        最近更新 更多