[英]Replacing words with conditions
I would need to check if a row contains a number (n), a blank space and a word in the list (house, houses, casa, case), in order to replace it with我需要检查一行是否包含一个数字 (n)、一个空格和列表中的一个单词(house、houses、casa、case),以便将其替换为
10.00
if the number is equal to 1
; 10.00
如果数字等于1
;10.00*n
where n
is a number not equal to 1
. 10.00*n
其中n
是不等于1
的数字。Example:例子:
H_C
4 case
9 apart
1 house
Expected output预期 output
H_C New_H_C
4 case 40.00
9 apart 9 apart
1 house 10.00
I have tried using a mix of re.search
looking at the list (house, houses,case,casa), and strip
for adding .00
, but I am confused on how to use it to determine the conditions 10.00
and 10.00*n
.我尝试使用re.search
的组合查看列表(house、houses、case、casa)和strip
以添加.00
,但我对如何使用它来确定条件10.00
和10.00*n
感到困惑。
I hope you can help me.我希望你能帮助我。
You can do this regex:您可以执行此正则表达式:
words = ['house', 'houses', 'casa', 'case']
# extract the relevant numbers
s = df.H_C.str.extract(f'(\d+) ({"|".join(words)})')[0].astype(float)
# multiply with 20
# you can search for `format` string function
df['New_H_C'] = np.where(s.notna(),s.apply(lambda x:'{:.02f}'.format(x)),
df['H_C'])
Output: Output:
H_C New_H_C
0 4 case 4.00
1 9 apart 9 apart
2 1 house 1.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.