簡體   English   中英

檢查字符串中是否存在兩個子字符串中的任何一個

[英]check if either of two substrings exist in a string

我正在使用以下代碼替換所有-並從我的 dataframe 列,刪除所有

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"字符串。 怎么了?

使用DataFrame.replace with regex=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
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM