使用Python在Jupyter Notebook读取CSV文件匹配适宜种植作物
作物匹配功能实现代码
首先确保你的Python环境已安装pandas库,若未安装可在Jupyter Notebook中先执行以下命令安装:!pip install pandas
完整实现代码如下:
import pandas as pd # 读取Crops.csv文件,若文件和notebook不在同一路径,需填写文件的绝对路径 crop_df = pd.read_csv("Crops.csv") # 定义输入的三个环境参数 input_temperature = 23.5 input_ph = 17 input_humidity = 23.4 # 筛选同时匹配三个参数的作物记录 matched_rows = crop_df[ (crop_df["Temperature"] == input_temperature) & (crop_df["PH"] == input_ph) & (crop_df["Humidity"] == input_humidity) ] if not matched_rows.empty: suitable_crop = matched_rows["Suitable crop to Grow"].iloc[0] print(f"适宜种植的作物是'{suitable_crop}'") else: print("当前输入参数未匹配到适宜种植的作物")
注意事项
- 若存在浮点精度匹配问题,可以将等值判断改为差值小于极小阈值的判断,例如将温度匹配规则改为
abs(crop_df["Temperature"] - input_temperature) < 1e-6,避免浮点存储误差导致匹配失败 - 若CSV文件存在多个完全匹配的记录,上述代码会默认返回第一条匹配的作物
内容的提问来源于stack exchange,提问作者Pradeep GN
相关产品推荐
相关产品推荐

