[英]Pandas slice row by index list for column
I have this pandas dataframe:我有这个 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: df0 然后返回:
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.我认为 pandas 切片尝试在列表中为每一行应用相同的每个索引。 Any help appreciated.
任何帮助表示赞赏。 Thank you.
谢谢你。
You can try rsplit
你可以试试
rsplit
df0['rate'] = df0['county'].str.rsplit(' ', n = 1).str[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.