Pandas slice row by index list for column

Viewed 76

I have this pandas dataframe:

                           county reporting_code
0           other locality rate %           code
1           New York State only 4           0021
2                        Albany 8           0181
3                   Allegany 81/2           0221

I would like it to be:

                           county reporting_code  rate
0           other locality rate %           code   %
1           New York State only 4           0021   4
2                        Albany 8           0181   8
3                   Allegany 81/2           0221   81/2

I need to extract the numbers in the county column into a new column and convert them to decimals. I get the index of the last space in the county column:

indx = (df0['county'].str.rindex(' '))

indx returns:

0     19
1     19
2      6
3      8

I then try:

df0['rate'] = df0['county'].str.slice(start=indx)

df0 then returns:

                           county reporting_code  rate
0           other locality rate %           code   NaN
1           New York State only 4           0021   NaN
2                        Albany 8           0181   NaN
3                   Allegany 81/2           0221   NaN

I think pandas slice tries to apply the same each index in the list for each row. Any help appreciated. Thank you.

1 Answers

You can try rsplit

df0['rate'] = df0['county'].str.rsplit(' ', n = 1).str[-1]
Related