从csv文件中读取行的每列数据,并应用基于列索引的公式



我在CSV文件中有一个土壤样本

pH    K      Zn      Fe  Cu     Mn
Soil 1  7.74 279    0.48    6.4 0.21    4.7
Soil 2  9.02 247    0.27    6.4 0.16    5.6
Soil 3  7.8  265    0.46    6.2 0.51    6.1
Soil 4  8.36 127    0.5     3.1 0.28    2.3

我需要阅读每个土壤样本,对于每个元素,我需要添加一个特定的公式来检查土壤是低肥力、不肥沃还是肥沃。

我的概念是将CSV转换为列表,然后从收到的2D列表中,我可以迭代行中的每个元素,并检查每个营养素的参数。

我使用了以下代码:

import csv
import pandas as pd
from pandas import DataFrame
with open('datan.csv', newline='') as soil_file: #CSV datafile
soil_reader = csv.reader(soil_file)
data = list(soil_reader)
data.pop(0) #first row is string
for i in data:
for j in i: #iterate through each element of the row
if((float(j) >= 5.1 and float(j) <= 6.5) or (float(j) >= 7.6 and float(j) <= 8.5)):
print("Soil is low fertile")  #condition
elif((float(j) < 5) or (float(j) > 8.5)):
print("Soil is Non fertile")
else:
print("Soil is fertile")

问题是,循环从第一个元素开始,一直到最后一行的末尾,而不停在行的末尾,并且在所有情况下,条件都是true。所以我得到了所有24个元素的结果。

我需要的是,循环应该检查第一个土壤样本并打印结果,然后转到下一个土壤样本。

我不知道如何在这里实现panda,但在某个地方读到,通过Dataframe,我可以使用读取索引

df.index

但是它读取的是整列而不是整行!我需要的有点像:

for Soil 1:
if df[index] == 'ph':
Use func pH()
elif df[index] == 'K':
Use func K()

等等…

附言:我犯了一个愚蠢的错误,没有在循环中添加计数器

我在代码中做了一些更改,现在循环在读取第一个元素后停止,但不检查函数中的其他条件。

import csv
import pandas as pd
from pandas import DataFrame

def pH(j):
if ((float(j) >= 5.1 and float(j) <= 6.5) or (float(j) >= 7.6 and float(j) <= 8.5)):
print("Soil is low fertile")
def pH(j):
if ((float(j) >= 5.1 and float(j) <= 6.5) or (float(j) >= 7.6 and float(j) <= 8.5)):
print("Soil is low fertile")
return
elif ((float(j) < 5) or (float(j) > 8.5)):
print("Soil is Non fertile")
return
else:
print("Soil is fertile")
return
elif ((float(j) < 5) or (float(j) > 8.5)):
print("Soil is Non fertile")
return
else:
print("Soil is fertile")
return
with open('datan.csv', newline='') as soil_file:
soil_reader = csv.reader(soil_file)
data = list(soil_reader)
data.pop(0)
#print(data, end="n")
n=0
for i in data:
for j in i:
n=n+1
if n==1:
pH(j)
continue

谢谢!

您可以使用df['pH']或df.pH(如果列名没有空格或特殊字符(直接访问列

你同意再写一个代表生育率的专栏吗?还是你一定想要打印声明(想在评论中提问,但没有足够的声誉(

对于代表生育率的另一列,你可以使用loc并通过你的过滤器

df.loc[df.ph>=5.1,"fertility"] = "fertile"

用于循环浏览您的列:

for col in df.columns:
# displaying 
display(df.loc[df[col]>6])

如果你只有多个输出和每个输出的公式,你可以使用:

filter_criteria = {"fertile":(df.pH>8)&(df.K<200),"non-fertile":(df.pH>7.5)&(df.K>240),"low":(df.pH>7.5)&(df.K>270)}
for key in filter_criteria.keys():
df.loc[filter_criteria[key],"fertility"] = key

最新更新