Remove the word in a string

Hi ALL,

I do have a scenario that in a dataframe has the column values

col1
abc/bcv/hyr/jki_ty
abc/bcfg/hyj_tg

I need to remove the string with comes at the end after last ‘/’
output should be
col
abc/bcv/hyr
abc/bcfg

Can abybody tell me what best I can do here.

Thanks

DataFrame has functions to work with strings - similar to normal string - but with prefix .str

This split on last / and create lists with all values

df['col'].str.rsplit('/', 1)

and this get only first value from this list

df['col'].str.rsplit('/', 1).str[0]

I think you could ask for this on Stackoverflow.com with tag pandas

https://stackoverflow.com/questions/tagged/pandas

See also pandas documentation: Working with text data


Minimal working example

import pandas as pd

data = {
    'col': [
        'abc/bcv/hyr/jki_ty',
        'abc/bcfg/hyj_tg'
    ], 
}

df = pd.DataFrame(data)

df['col'] = df['col'].str.rsplit('/', 1).str[0]

print(df['col'])

Result

0    abc/bcv/hyr
1       abc/bcfg
Name: col, dtype: object
© Copyright 2013-2021 Analytics Vidhya