基于Regex的
str.replace
此正则表达式模式具有
str.replace
应该做得很好。
s.str.replace(r'\.(?=.*?\.)', '')
0 1234.5
1 123.5
2 2345.6
3 678.9
dtype: object
这个想法是,只要有更多的字符需要替换,就要不断替换。下面是所用正则表达式的分解。
\. # '.'
(?= # positive lookahead
.*? # match anything
\. # look for '.'
)
玩得开心
np.vectorize
如果要使用
count
,这不是不可能的,但这是一个挑战。您可以使用
np。矢量化
. 首先,定义一个函数,
def foo(r, c):
return r.replace('.', '', c)
矢量化,
v = np.vectorize(foo)
现在,调用函数
v
,通过
s
以及要替换的计数。
pd.Series(v(s, s.str.count(r'\.') - 1))
0 1234.5
1 123.5
2 2345.6
3 678.9
dtype: object
请记住,这基本上是一个美化的循环。
循环/列表理解
python等效于
vectorize
可能是,
r = []
for x, y in zip(s, s.str.count(r'\.') - 1):
r.append(x.replace('.', '', y))
pd.Series(r)
0 1234.5
1 123.5
2 2345.6
3 678.9
dtype: object
或者,使用列表理解:
pd.Series([x.replace('.', '', y) for x, y in zip(s, s.str.count(r'\.') - 1)])
0 1234.5
1 123.5
2 2345.6
3 678.9
dtype: object