2017-09-18 140 views
-1

我是Python的初學者,我將它用於我的項目。如何從Python中的CSV文件行查找最小值?

我想提取從CSV文件的column4最小值,我不知道如何。

我可以打印整列[4]但我不知道如何從列打印最小值(只是一列)[4]。

CSV文件:https://www.emcsg.com/marketdata/priceinformation 我下載統一新加坡能源價格&需求預測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] 
+1

你有一些代碼;請在問題本身提供[mcve]。 –

+0

您將行更改爲列,所以我編輯了我的答案。另外,請注意Python中的縮進。 – Alperen

回答

0

不知道如何你是在讀值。但是,您可以添加所有的值和列表,然後:

list = [] 
<loop to extract values> 
list.insert(index, value) 
min_value = min(list) 

注:指數是其中的價值得到插入「地點」。

0

編輯2: 解列無大熊貓模塊:

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 
+0

所以你刪除第一個字符?爲什麼?你爲什麼假設如果字符串可以被解析,它是一個想要的值? – Acccumulation

+0

1)我可以選擇不刪除第一行,無論如何都不能將其解析爲浮動。 2)我們試圖在列表中找到最小數量。如果它不能被解析爲一個浮點數,它甚至不是一個數字。我們如何選擇這個字符串作爲最小值?如果可以解析,我將它添加到列表中。最後,我調用了min()函數,這裏是我找到想要的數字的地方。 – Alperen

+0

感謝您的編輯!我需要安裝「將pandas導入爲pd」,對嗎?有沒有辦法做到這一點沒有/熊貓'? – Autumn

0

你的措辭是有點不明確的。起初,我認爲你的意思是第四行的最小值,但是看看你想要的數據至少是第四列(USEP($/MWh))。爲此,(假設 「Realtime_Sep-2017.csv」 是文件名),你可以這樣做:

import pandas as pd 
df = pd.read_csv("Realtime_Sep-2017.csv") 
print(min(df["USEP($/MWh)"]) 

其他選項包括df.min() 「USEP($ /兆瓦時)」],df.min ()[4],和分鐘(df.iloc [:,4])

+0

是的,對不起,我的意思是專欄。我試了一下代碼,它說'無效的語法',並在下一行出現紅色的一行。是因爲我使用的是舊版本的Python嗎? (Python 2.7.13) – Autumn

+0

隔離什麼語法無效。 df [「USEP($/MWh)」]是否有效? df.iloc [:,4]? df.min()? – Acccumulation

相關問題