如何在Pandas DataFrame中根据用户输入的ID获取对应价格?
获取Pandas DataFrame中对应ID的价格
嘿,作为刚接触Python和Pandas的新手,这个需求其实很典型,我来给你一步步讲清楚怎么实现~
首先先把你的DataFrame构造出来(方便后续测试和运行):
import pandas as pd # 构造你提供的DataFrame data = { 'ID': [1, 2, 3], 'Name': ['Apple', 'Orange', 'Pear'], 'Price': [1, 0.5, 0.7] } df = pd.DataFrame(data)
接下来你已经写了输入代码,需要做两个关键调整,就能实现需求:
- 把输入的字符串转换成整数类型(因为你的DataFrame里ID是整数,类型匹配才能准确查找)
- 用Pandas的查找方法定位对应Price值
基础实现方案(适合新手理解)
inputid = int(input("Please input ID: ")) # 转成int,和DataFrame的ID类型匹配 # 用loc定位符合条件的行,提取Price列,再取第一个元素 try: price = df.loc[df['ID'] == inputid, 'Price'].iloc[0] print(f"The price is: {price}") except IndexError: print(f"ID {inputid} not found in the DataFrame!")
为什么这么写?
df.loc[df['ID'] == inputid, 'Price']:这部分会返回一个Series对象(类似一维数组),包含所有ID匹配的Price值.iloc[0]:因为你的ID应该是唯一的,所以取第一个元素就是你要的目标价格try-except:防止用户输入不存在的ID导致代码报错,提升代码的健壮性
更高效的进阶方案(如果ID是唯一标识符)
如果你的ID是唯一的,可以把ID设为DataFrame的索引,这样查找会更直观、更高效:
# 把ID设为DataFrame的索引 df.set_index('ID', inplace=True) inputid = int(input("Please input ID: ")) try: price = df.loc[inputid, 'Price'] print(f"The price is: {price}") except KeyError: print(f"ID {inputid} not found in the DataFrame!")
这种方式不需要写条件判断,直接通过索引定位,代码更简洁。
内容的提问来源于stack exchange,提问作者vvv-1234
相关产品推荐
相关产品推荐

