Stripping string values at different positions

Viewed 41

Suppose I have the following dataframe:

df = pd.DataFrame({'X':['AB_123_CD','EF_123CD','XY_Z'],'Y':[1,2,3]})
           X  Y
0  AB_123_CD  1
1   EF_123CD  2
2       XY_Z  3

I want to use strip method to get rid of the first prefix such that I get

        X  Y
0  123_CD  1
1   123CD  2
2       Z  3

I tried doing: df.X.str.split('_').str[-1].str.strip() but since the positions of _'s are different it returns different result to the one desired above. I wonder how can I address this issue?

5 Answers

You're close, you can split once (n=1) from the left and keep the second one (str[1]):

df.X = df.X.str.split("_", n=1).str[1]

to get

>>> df

        X  Y
0  123_CD  1
1   123CD  2
2       Z  3

Try this instead:

df["X"] = df["X"].apply(lambda x: x[x.find("_")+1:])
>>> df 
        X  Y
0  123_CD  1
1   123CD  2
2       Z  3

This keeps the entire string after the first occurence of _

The following code could do the job:

df['X'] = df.X.apply(lambda x: '_'.join(x.split('_')[1:]))

Your solution is very close. With some minor changes, it should work:

df.X.str.split('_').str[1:].str.join('_')

0    123_CD
1     123CD
2         Z
Name: X, dtype: object

You can define maxsplit in the str.split() function. It sounds like you just want to split with maxsplit 1 and take the last element:

df['X'] = df['X'].apply(lambda x: x.split('_',1)[-1])
Related