[英]Replace only replacing the 1st argument
I have the following code:我有以下代码:
df['Price'] = df['Price'].replace(regex={'$': 1, '$$': 2, '$$$': 3})
df['Price'].fillna(0)
but even if a row had "$$" or "$$$" it still replaces it with a 1.0.但即使一行有 "$$" 或 "$$$" 它仍然用 1.0.0 替换它。
How can I make it appropriately replace $ with 1, $$ with 2, and $$$ with 3?我怎样才能使它适当地用 1 替换 $,用 2 替换 $$,用 3 替换 $$$?
df.Price.map({'$': 1, '$$': 2, '$$$': 3})
Assuming you really want to use regex matching and not a simple map
, you need to fix 2 things.假设您真的想使用正则表达式匹配而不是简单的
map
,您需要修复两件事。
1- escape $
which means end of string in regex 1- 转义
$
表示正则表达式中字符串的结尾
2- put the patterns in reverse order of length in the dictionary to have $$$ be evaluated before $$ and before $ ( {r'\$\$\$': 3, r'\$\$': 2, r'\$': 1}
) 2-将模式以长度相反的顺序放入字典中,以便在 $$ 之前和 $ 之前评估 $$$ (
{r'\$\$\$': 3, r'\$\$': 2, r'\$': 1}
)
Example:例子:
df = pd.DataFrame({'price': ['abc $', 'def $$', '$$$']})
df['new'] = df['price'].replace(regex={r'\$\$\$': 3, r'\$\$': 2, r'\$': 1})
Output: Output:
price new
0 abc $ 1
1 def $$ 2
2 $$$ 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.