How to extract the second instance of integer value in a string

Viewed 212

Suppose I have a DataFrame with one column having values like ABC_S22_F1, ABD_P23_H3,ABE_Q25_K3. When I do df['col1'] = df['Column_Name'].str.extract('(\d+)').astype(int), I get the first instance of Integer (i.e 22,23,25) in new column col1. I want col2 to have second instance of integer having values 1 3 3.

1 Answers

Use Series.str.findall for extract all integers and then select second value of lists:

df['col1'] = df['Column_Name'].str.findall('(\d+)').str[1].astype(int)
print (df)
  Column_Name col1
0  ABC_S22_F1    1
1  ABD_P23_H3    3
2  ABE_Q25_K3    3
Related