Pandas: Split string on last occurrence

Viewed 6405

I'm trying to split a column in a pandas dataframe based on a separator character, and obtain the last section.

pandas has the str.rsplit and the str.rpartition functions.

If I try:

df_client["Subject"].str.rsplit("-", 1)

I get

0 [Activity -Location , UserCode]
1 [Activity -Location , UserCode]

and if I try

df_client["Subject"].str.rpartition("-")

I get

      0            1      2   

0 Activity -Location - UserCode
1 Activity -Location - UserCode

If I do

df_client["Subject"].str.rpartition("-")[2]

I get

0 UserCode

which is what I want.

To me, str.rsplit seems unintuitive.

After getting the list of the split string, how would I then select the single item that I need?

2 Answers

I think need indexing by str working with iterables:

#select last lists 
df_client["Subject"].str.rsplit("-", 1).str[-1]
#select second lists
df_client["Subject"].str.rsplit("-", 1).str[1]

If performance is important use list comprehension:

df_client['last_col'] = [x.rsplit("-", 1)[-1] for x in df_client["Subject"]]
print (df_client)
                      Subject  last_col
0  Activity-Location-UserCode  UserCode
1  Activity-Location-UserCode  UserCode

Use expand=True:

df_client["Subject"].str.split('-', expand=True)[2]
Related