如果字符存在,如何从特定索引中删除熊猫列中的字符

时间:2019-08-12 17:06:44

标签: python python-3.x pandas

我有一个pandas列,如果字符等于'F',我想删除最后一个字符。

2 个答案:

答案 0 :(得分:2)

查看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_

答案 1 :(得分:1)

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

如果您想同时删除最后一个case=False'F',请添加'f'作为参数


样本数据

import pandas as pd
df = pd.DataFrame({'col': ['Foo', 'bar', 'oFF', 'OF', 'tof']})
相关问题