【问题标题】:Python / pandas function to replace '-' negative sign but not negative sign in negative numbers ( '-' in '-1')Python / pandas函数替换负数中的'-'负号而不是负号('-1'中的'-')
【发布时间】:2022-01-22 23:28:15
【问题描述】:

我有一个 pandas 数据框,其中包含 - 缺失值, 如果我使用.replace('-','NaN'),它会将 -1 替换为 NaN1 我怎样才能只删除 - 签名但不 - 如果它是 -1

数据框示例

Co1_1 Values
Pine  -
Apple -1
Mango 2
Berry -
Banana -3

这里我想替换 - 在 Pine & Berry 中,而不是在香蕉中

【问题讨论】:

  • 试试df['col'].str.replace(r'-(?=\d)', '', regex=True)

标签: python pandas data-manipulation


【解决方案1】:

根本不需要.replace()。找到包含破折号的单元格,并更新它们:

df[df['Values'] == '-'] = np.nan

请记住,'NaN' 不是 NaN:它是一个看起来像 NaN 的字符串。 “真正的”NaN 是来自 numpy 的 np.nan

【讨论】:

    【解决方案2】:

    您可以将列的值转换为数字。那么也许- 会被0 替换,不确定你是否想要它:

    pandas.to_numeric(arg, errors='raise', downcast=None)
    

    Reference


    如果不起作用,astype 可能是一个替代方案

    DataFrame.astype(dtype, copy=True, errors='raise')
    # Example :
    df.astype({'values': int})
    

    Reference


    然而最优雅的解决方案,最常用的是使用熊猫选择器:

    df[ df['Values'] == '-' ] = np.nan
    

    您还可以选择将值 - 替换为您想要的任何值:0Nan(np.nan)等

    【讨论】:

      【解决方案3】:

      因此,如果您首先评估要检查的值的长度(转换为字符串),那么当您删除长度为 1 的条目时,您可以确保只选择“-”条目。

      for values:
          if len(str(value)) == 1:
              value.replace(...)
      

      但我确信有更优雅的方式;D

      【讨论】:

      • 这甚至不是有效的 Python。
      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 2019-06-10
      • 2017-03-20
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      相关资源
      最近更新 更多