簡體   English   中英

如果字符存在,如何從特定索引中刪除熊貓列中的字符

[英]How to remove character in pandas column from specific index if character exists

我有一個pandas列,如果字符等於'F',我想刪除最后一個字符。

看看pandas.Series.str.endswith

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM