如何解决将int应用于单元素Series时的FutureWarning?
解决U.S. States Game中的FutureWarning警告
警告的根源是代码里直接对单元素的Pandas Series调用int()转换,这种写法已被弃用。具体问题出在这两行:
t.goto(int(state_data.x), int(state_data.y))
state_data.x和state_data.y是匹配到对应州后的单元素Series,直接转int的方式在后续Pandas版本会报错,官方提示改用iloc[0]定位到唯一元素后再转换。
两种可行的修改方式:
- 按照警告提示用
iloc[0]:
t.goto(int(state_data.x.iloc[0]), int(state_data.y.iloc[0]))
- 用
item()方法更简洁(自动提取单元素值并返回Python原生类型,无需额外转int):
t.goto(state_data.x.item(), state_data.y.item())
修改后的完整代码:
import turtle import pandas FONT = 'monaco', 10, "bold" screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("50_states.csv") all_states = data.state.to_list() answer_state = screen.textinput(title="Guess the state name", prompt="Whats another state name?").title() print(answer_state) if answer_state in all_states: t = turtle.Turtle() t.hideturtle() t.penup() state_data = data[data.state == answer_state] # 这里用item()方法替换原写法 t.goto(state_data.x.item(), state_data.y.item()) t.write(answer_state, font=FONT) screen.exitonclick()
内容的提问来源于stack exchange,提问作者Siddhant Baghel
相关产品推荐
相关产品推荐

