I have this dataframe in pandas
path variable
0 /home/opt/chat A
1 /home/test B
2 /home/opt/projects C
3 /home/opt/projects/ex/remove/results D
How do I strip the column path to return this output in my dataframe?
path variable
0 chat A
1 test B
2 projects C
3 results D
CodePudding user response:
You can use rsplit
with n=1
, to limit to one split:
df['path'] = df['path'].str.rsplit('/', n=1).str[-1]
or, maybe better, str.extract
with a short regex ([^/] $)
(any series of non-/
characters [^/]
, just before the end of line $
):
df['path'] = df['path'].str.extract(r'([^/] $)', expand=False)
output:
path variable
0 chat A
1 test B
2 projects C
3 results D
CodePudding user response:
Use Series.str.split
wth select last value by indexing:
df['path'] = df['path'].astype(str).str.split('/').str[-1]
print (df)
path variable
0 chat A
1 test B
2 projects C
3 results D