【问题标题】:How to replace values by None if string contains character pattern?如果字符串包含字符模式,如何用 None 替换值?
【发布时间】:2021-06-07 17:15:31
【问题描述】:

我想替换我的 pandas df 列 departments 中的每个字符串 用 None 如果它包含 )

         departments   var1   var1.1
   1      transport     aa      uu
   2      industry)     bb      tt
   3      aviation)     cc      tt

数据集应该是什么样子

         departments   var1    var2
   1      transport     aa      uu
   2      None          bb      tt
   3      None          cc      tt

这里有一个类似的解决方案: Replacing regex pattern with another string works, but replacing with NONE replaces all values

由于我不使用 spark,如何将其转换为基础 python?

df.withColumn("departments", when(col("departments").rlike("\)"), None)
          .otherwise(col("departments"))
      )

【问题讨论】:

  • 那么上面的df是pandas df还是spark df?
  • 我的 df 是熊猫 df

标签: python-3.x pandas string nonetype


【解决方案1】:

使用您展示的示例,请尝试以下操作。您可以使用str.contains 函数找出departments 列中的任何值具有),然后使用.loc 来获取我们在m 变量中设置为None 的值。

m = df['departments'].str.contains('\)', na=False)
df.loc[m,'departments'] = None

【讨论】:

  • ValueError: 无法使用包含 NA / NaN 值的非布尔数组进行屏蔽。在将数组用作掩码之前,需要用 True 或 False 显式填充缺失值。
  • @id345678,当然,我已经编辑了我的答案,请看一下,然后告诉我进展如何。
猜你喜欢
  • 2014-12-17
  • 2018-08-01
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-08-08
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多