![](/img/trans.png)
[英]Check if particular string exist in text either at first or second position
[英]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.