簡體   English   中英

使用 Python 使用輸入文件作為 csv 的 Jupyter Notebook 中給出的輸入獲取 output 的代碼

[英]Code to get the output based on the input given in Jupyter Notebook using Python using input file as csv

我有名為 Crops 的 csv 文件。 文件包含 4 列,如下所述。

溫度 PH 濕度 適合種植的作物 20.5 15 30.2 水稻 21.5 16 26.6 小米 23.5 17 23.4 玉米

因此,如果溫度、PH 和濕度的輸入為 23.5、17 和 23.4,則 output 應顯示為適合種植的作物是“玉米”

提前致謝

您可以使用Pandas快速執行此操作

import pandas as pd

crops_data = pd.read_csv(FILEPATH)

temperature_input = float(input("Enter Temperature: "))
ph_input = float(input("Enter pH: "))
humidity_input = float(input("Enter Humidity: "))

data_filter = (crops_data["Temperature"] == temperature_input) & (crops_data["PH"] == ph_input) & (crops_data["Humidity"] == humidity_input)
suitable_crop = crops_data.loc[data_filter]["Suitable crop to Grow"].values[0]

print(suitable_crop)

查看Pandas 文檔以獲取有關如何使用它的更多信息


雖然,對於這么簡單的任務,Pandas 感覺有點矯枉過正

因此,您可以直接閱讀 CSV 並進行一些基本比較以獲得您的數據

CSV = []

with open(FILEPATH, 'r') as csv_file:
    CSV = csv_file.read().split()[1:]

temperature_input = float(input("Enter Temperature: "))
ph_input = float(input("Enter pH: "))
humidity_input = float(input("Enter Humidity: "))

filter_string = "%g,%g,%g" % (temperature_input, ph_input, humidity_input)
filter_result : str

for LINE in CSV:
    if filter_string in LINE:
        filter_result = LINE.split(',')[-1]

print(filter_result)

您可以對filter_string有點創意以獲得其他結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM