user11218700
user11218700

Reputation:

Get data after second underscore from back in python dataframe?

I'm trying to get data after second underscore from back in python dataframe?

    number
0   a_bc_def 12_23_this_6729
1   abc_def,122$3_this_6729
2   abc_def_1_2_23_this_6729


    number
0   this_6729
1   this_6729
2   this_6729

I tried to get data from second underscore from beginning.

df['number'] = df['number'].str.split('_',2).apply(lambda x: x[-1])

How to do that from second underscore from back ?

Upvotes: 1

Views: 1560

Answers (2)

G. Anderson
G. Anderson

Reputation: 5955

No need for apply, this can be done with str method operations

str.split('_') to split on underscores

str[-2:] to select the last 2 elements post-split

str.join('_') to join those elements into a single string

df['number']=df['number'].str.split('_').str[-2:].str.join('_')

0    this_6729
1    this_6729
2    this_6729

Upvotes: 1

sam
sam

Reputation: 2311

One way could be to reverse the string for the same, do the operation, and reverse again.

df['number'].apply(lambda x: str(x)[::-1].split('_',2)[-1][::-1])

It's not very efficient since you need to reverse twice, but of strings are not too long this will not be that bad in my opinion.

Upvotes: 0

Related Questions