![](/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.