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.
You can try rsplit
df0['rate'] = df0['county'].str.rsplit(' ', n = 1).str[-1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.