IndexError: string index out of range - if function with dataframe
IndexError: string index out of range - if function with dataframe
我尝试消除数据框中的括号和不必要的标记。
这是我的数据:
df["address"]
index address
0 (#)(△)Kaohsiung City
1 (△)New Taipei City
2 (O)Chiayi City
.
.
目前我正在使用这个:
def reshape_address(addr):
if addr[0] == "(":
return addr.split(")", 1)[-1]
else:
return addr
def run_reshape_addr(text):
text["address"] = text["address"].apply(reshape_address)
text["address"] = text["address"].apply(reshape_address)
text["address"] = text["address"].apply(reshape_address)
#run three times in order to get rid of multiple brackets
run_reshape_addr(df)
不知何故我得到了 IndexError: 字符串索引超出范围。
但是,这运行之后,部分数据已经执行成功,甚至弹出错误信息。
我该如何修改?为什么有些数据在这种情况下仍然在执行?谢谢。
您很可能有一个包含空字符串的记录,因此当您查看它是否以 (
开头时,它会抛出 IndexError
.
您可以通过先检查字符串是否为空来解决此问题。
def reshape_address(addr):
if addr and addr[0] == "(": # Check if addr is truthy
return addr.split(")", 1)[-1]
else:
return addr
您可以使用 rpartition
一次性删除所有前面的 (...)
:
def run_reshape_addr(text):
_, _, text["address"] = text["address"].rpartition(")")
a = "Correct-Horse-Battery-Staple"
b = "Troubadour"
a.rpartition("-") == ("Correct-Horse-Battery", "-", "Staple")
b.rpartition("-") == ("", "", "Troubadour")
我尝试消除数据框中的括号和不必要的标记。
这是我的数据:
df["address"]
index address
0 (#)(△)Kaohsiung City
1 (△)New Taipei City
2 (O)Chiayi City
.
.
目前我正在使用这个:
def reshape_address(addr):
if addr[0] == "(":
return addr.split(")", 1)[-1]
else:
return addr
def run_reshape_addr(text):
text["address"] = text["address"].apply(reshape_address)
text["address"] = text["address"].apply(reshape_address)
text["address"] = text["address"].apply(reshape_address)
#run three times in order to get rid of multiple brackets
run_reshape_addr(df)
不知何故我得到了 IndexError: 字符串索引超出范围。 但是,这运行之后,部分数据已经执行成功,甚至弹出错误信息。
我该如何修改?为什么有些数据在这种情况下仍然在执行?谢谢。
您很可能有一个包含空字符串的记录,因此当您查看它是否以 (
开头时,它会抛出 IndexError
.
您可以通过先检查字符串是否为空来解决此问题。
def reshape_address(addr):
if addr and addr[0] == "(": # Check if addr is truthy
return addr.split(")", 1)[-1]
else:
return addr
您可以使用 rpartition
一次性删除所有前面的 (...)
:
def run_reshape_addr(text):
_, _, text["address"] = text["address"].rpartition(")")
a = "Correct-Horse-Battery-Staple"
b = "Troubadour"
a.rpartition("-") == ("Correct-Horse-Battery", "-", "Staple")
b.rpartition("-") == ("", "", "Troubadour")