0

I just started to learn python. I have a csv file contains three row: date, time and temperature. Now I want to screen all temperature data > 80 and then put the screened lines into a list and print them.

import csv
date_array = []
time_array = []
temp_array = []
output = []

with open("/Users/Fay/Documents/GitHub/warning_system/temp.csv") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    next(csv_reader, None)
    for row in csv_reader:
        date_array.append(row[0])
        time_array.append(row[1])
        temp_array.append(row[2])
        #why to disassemble the data vertically instead of horizontally, line by line. 
    #print(data_array[1])
    #print(time_array[1])
    #print(temp_array[1])


    for row in csv_reader:
        output= ['data_array','time_array','temp_array']
       if temp_array > '80':
    print(output)

Could you help me to fix it? Thanks.

2
  • 1
    You need to indent your code correctly. Commented Mar 21, 2019 at 16:36
  • 1
    Don't make 3 separate arrays. Make an array of tuples or dictionaries, so all the related data is together. Commented Mar 21, 2019 at 16:37

1 Answer 1

1

Make an array of dictionaries, not 3 separate arrays.

The second loop should iterate over the array that you filled in, not csv_reader. There's nothing left to process in csv_reader, because the previous loop reached the end of it.

You should also convert the temperature to a number.

import csv
data_array = []
output = []

with open("/Users/Fay/Documents/GitHub/warning_system/temp.csv") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    next(csv_reader, None)
    for row in csv_reader:
        data_array.append({"date": row[0], "time": row[1], "temp": float(row[2])})

for item in data_array:
    if item['temp'] > 80:
        output.append(item)

print(output)
Sign up to request clarification or add additional context in comments.

4 Comments

Hi Barmar, thanks for your answer. But when I run the code, it comes out the following result. Is there any way to remove "date" "time" and "temp" in each element? [{'date': '1/2/2018', 'time': '5:00:00 PM', 'temp': 80.4}, {'date': '1/2/2018', 'time': '6:00:00 PM', 'temp': 81.6}, {'date': '1/2/2018', 'time': '7:00:00 PM', 'temp': 82.8}, {'date': '1/2/2018', 'time': '8:00:00 PM', 'temp': 84.0}, {'date': '1/2/2018', 'time...
Why don't you want them? Your code appends them to date_array and time_array.
So I cannot use this way to generate a dictionary that only contains the items then?
You can leave them out of the dictionary if you want. But what's the purpose of the dictionary then? The point is to keep related data together, not put them in separate arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.