我是Python的初学者,我正在将它用于我的项目。
我想从CSV文件的第4列中提取最小值,但我不确定如何操作。
我可以打印整个列[4],但不确定如何从列[4]打印最小值(只有一列)。
CSV文件:https://www.emcsg.com/marketdata/priceinformation 我正在下载Uniform Singapore Energy Price& 9月9日需求预测
提前谢谢你。
这是我目前的代码:
import csv
import operator
with open('sep.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
header = next(readCSV)
data = []
for row in readCSV:
Date = row[0]
Time = row[1]
Demand = row[2]
RCL = row[3]
USEP = row [4]
EHEUR = row [5]
LCP = row[6]
Regulations = row[7]
Primary = row[8]
Secondary = row[9]
Contingency = row[10]
Last_Updated = row[11]
print header[4]
print row[4]
答案 0 :(得分:0)
不确定你是如何读取这些值的。但是,您可以将所有值添加到和列表,然后:
list = []
<loop to extract values>
list.insert(index, value)
min_value = min(list)
注意:index是插入值的'place'。
答案 1 :(得分:0)
编辑2: 没有pandas模块的列的解决方案:
with open("Realtime_Sep-2017.csv") as file:
lines = file.read().split("\n") #Read lines
num_list = []
for line in lines:
try:
item = line.split(",")[4][1:-1] #Choose 4th column and delete ""
num_list.append(float(item)) #Try to parse
except:
pass #If it can't parse, the string is not a number
print(max(num_list)) #Prints maximum value
print(min(num_list)) #Prints minimum value
输出:
81.92
79.83
编辑: 以下是专栏的解决方案:
import pandas as pd
df = pd.read_csv("Realtime_Sep-2017.csv")
row_count = df.shape[0]
column_list = []
for i in range(row_count):
item = df.at[i, df.columns.values[4]] #4th column
column_list.append(float(item)) #parse float and append list
print(max(column_list)) #Prints maximum value
print(min(column_list)) #Prints minimum value
编辑前:
(连续解决方案) 这是一个简单的代码块:
with open("Realtime_Sep-2017.csv") as file:
lines = file.read().split("\n") #Reading lines
num_list = []
line = lines[3] #Choosing 4th row.
for item in line.split(","):
try:
num_list.append(float(item[1:-1])) #Try to parse
except:
pass #If it can't parse, the string is not a number
print(max(num_list)) #Prints maximum value
print(min(num_list)) #Prints minimum value
答案 2 :(得分:0)
你的措词有点含糊不清。起初我认为你的意思是第四行的最小值,但看看你似乎想要第四列的最小值(USEP($ / MWh))的数据。为此,(假设&#34; Realtime_Sep-2017.csv&#34;是文件名),你可以这样做:
import pandas as pd
df = pd.read_csv("Realtime_Sep-2017.csv")
print(min(df["USEP($/MWh)"])
其他选项包括df.min()[&#34; USEP($ / MWh)&#34;],df.min()[4]和min(df.iloc [:,4])< / p>