You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas使用变量而非字面量检索行返回空DataFrame问题

问题:输入人数匹配DataFrame时返回空结果

运行以下自行车租赁系统的Python代码时,直接用prices[prices['Number of Persons']==2]能正常返回Number of Persons为2的所有行,但改为prices[prices['Number of Persons']==n]且输入n为2时,返回空DataFrame。

Python代码

import pandas as pd
print("***Welcome to Bike Rental System***")
n=input("Enter number of persons: ")
both=input("Enter number of females who are senior citizens(both category): ")
females=input("Enter the number of females who are not senior ciizen(senior category): ")
senior=input("Enter the number of people who are not females and are senior citizens(senior category): ")
hours=input("Enter the number of hours to rent: ")
prices=pd.read_csv('prices.csv')
#mask=(prices['Number of Persons']==n)#&(prices['Both']==both )&(prices['No. of females']==females)&(prices['No. of Senior Citizens']==senior)
desired_column=prices[prices['Number of Persons']==2]
print(n)
print(desired_column)

对应的prices.csv内容

Number of Persons,No. of Senior Citizens,No. of females,Both,Base Price (in rs/hr),Discount %,net_price,Blueprint
1,0,0,0,50,0,50,N
1,1,0,0,50,10,45,S
1,0,1,0,50,5,47.5,F
1,0,0,1,50,20,40,B
2,0,0,0,100,0,100,NN
2,1,0,0,100,5,95,NS
2,0,1,0,100,2.5,97.5,NF
2,0,0,1,100,10,90,NB
2,2,0,0,100,20,80,SS
2,1,1,0,100,15,85,SF
2,1,0,1,100,25,75,SB
2,0,2,0,100,10,90,FF
2,0,1,1,100,20,80,FB
2,0,0,2,100,30,70,BB

原因分析

input()函数默认返回字符串类型,而DataFrame中Number of Persons列的数值是整数类型。当你输入2时,变量n的值是字符串"2",和DataFrame里的整数2不相等,因此无法匹配到任何行,返回空DataFrame。

解决方案

将所有数值类的输入转换为整数类型(对应csv里的整数列),修改代码中输入变量的定义部分:

n = int(input("Enter number of persons: "))
both = int(input("Enter number of females who are senior citizens(both category): "))
females = int(input("Enter the number of females who are not senior ciizen(senior category): "))
senior = int(input("Enter the number of people who are not females and are senior citizens(senior category): "))
hours = int(input("Enter the number of hours to rent: "))

之后再使用desired_column=prices[prices['Number of Persons']==n]就能正常匹配到对应行。

内容的提问来源于stack exchange,提问作者Sourabh Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:10:55