![](/img/trans.png)
[英]Replace all but last occurrences of a character in a string with pandas
[英]Replace the last character in a string if it's a particular character in a dataframe Python Pandas
使用正则表达式匹配最后一个字符:
df['Mix'].str.replace('\.$','K',regex=True)
如果没有正则表达式,您可以使用.str.endswith('.')
或.str[-1] == '.'
过滤需要替换最后一个字符的行
mask = df['Mix'].str.endswith('.')
#mask = (df['Mix'].str[-1] == '.')
df['Mix'][mask] = df['Mix'][mask]....
但问题是replace
- 它会替换文本中的所有点。 它需要使用不同的方法 - 获取没有最后一个字符的文本.str[:-1]
并添加新的字符+ "K"
df['Mix'][mask] = df['Mix'][mask].str[:-1] + 'K'
import pandas as pd
df = pd.DataFrame({ 'Mix':['572.7.','44.44','99']})
mask = df['Mix'].str.endswith('.')
#mask = (df['Mix'].str[-1] == '.')
df['Mix'][mask] = df['Mix'][mask].str[:-1] + 'K'
print(df)
编辑:
与apply()
类似的方法(也没有regex
)
def modify(text):
if text.endswith('.'):
text = text[:-1] + 'K'
return text
df['Mix'] = df['Mix'].apply(modify)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.