【问题标题】:check if either of two substrings exist in a string检查字符串中是否存在两个子字符串中的任何一个
【发布时间】:2021-11-28 08:03:23
【问题描述】:

我正在使用以下代码替换所有 - 并从我的数据框列中删除所有 ,

df[['sale_price','mrp', 'discount', 'ratings', 'stars']]=df[['sale_price','mrp', 'discount', 'ratings', 'stars']].applymap(lambda r: np.nan if '-' in str(r) else str(r).replace(',', ''))

有些列是"nan"(不是 np.nan,而是字符串 nan)。要删除这些,我也会这样做

useless_strings=['-','nan']
df[['sale_price','mrp', 'discount', 'ratings', 'stars']]=df[['sale_price','mrp', 'discount', 'ratings', 'stars']].applymap(lambda r: np.nan if any(xx in str(r) for xx in useless_strings) else str(r).replace(',', ''))

这不会删除那些"nan" 字符串。怎么了?

【问题讨论】:

  • 这不会删除那些“nan”字符串。出了什么问题? 输出是什么?
  • 顺便说一句,您的代码中没有列表推导
  • @DaniMesejo,我想用np.nan 替换所有-"nan"

标签: python pandas string


【解决方案1】:

通过字典中定义的子字符串使用DataFrame.replaceregex=True

df = pd.DataFrame([['10,4','-','nan',5,'kkk-oo']],
                  columns=['sale_price','mrp', 'discount', 'ratings', 'stars'])
print (df)
  sale_price mrp discount  ratings   stars
0       10,4   -      nan        5  kkk-oo


useless_strings=['-','nan']
d = dict.fromkeys(useless_strings, np.nan)
d[','] = ''
print (d)
{'-': nan, 'nan': nan, ',': ''}

cols = ['sale_price','mrp', 'discount', 'ratings', 'stars']
df[cols] = df[cols].replace(d, regex=True)
print (df)
  sale_price  mrp  discount  ratings  stars
0        104  NaN       NaN        5    NaN
    

【讨论】:

  • @AmanArora - 是的,它按需要工作。
  • 如果字符串包含"-""nan",我想用np.nan替换字符串
  • @AmanArora - 答案已编辑。
猜你喜欢
  • 2022-11-16
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
  • 2021-07-10
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多