![](/img/trans.png)
[英]Better way to remove character from index column in this pandas dataframe?
[英]How to remove character in pandas column from specific index if character exists
我有一個pandas列,如果字符等於'F',我想刪除最后一個字符。
df = pd.DataFrame({
'col': ['test', 'test_f', 'test_F']
})
df['res'] = np.where(df['col'].str.endswith('F'), df['col'].str[:-1], df['col'])
col res
0 test test
1 test_f test_f
2 test_F test_
str.replace
df['col'].str.replace('F$', '')
# |
# Ensures it's the last
#0 Foo
#1 bar
#2 oF
#3 O
#4 tof
#Name: col, dtype: object
如果要同時刪除最后一個'F'
或'f'
添加case=False
作為參數
樣本數據
import pandas as pd
df = pd.DataFrame({'col': ['Foo', 'bar', 'oFF', 'OF', 'tof']})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.