[英]Pandas slice row by index list for column
我有這個 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
我希望它是:
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
我需要將縣列中的數字提取到一個新列中並將它們轉換為小數。 我得到縣列中最后一個空格的索引:
indx = (df0['county'].str.rindex(' '))
指數回報:
0 19
1 19
2 6
3 8
然后我嘗試:
df0['rate'] = df0['county'].str.slice(start=indx)
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
我認為 pandas 切片嘗試在列表中為每一行應用相同的每個索引。 任何幫助表示贊賞。 謝謝你。
你可以試試rsplit
df0['rate'] = df0['county'].str.rsplit(' ', n = 1).str[-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.