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.
TrebledJ
9,0237 gold badges28 silver badges50 bronze badges
-
1You need to indent your code correctly.Barmar– Barmar2019年03月21日 16:36:56 +00:00Commented Mar 21, 2019 at 16:36
-
1Don't make 3 separate arrays. Make an array of tuples or dictionaries, so all the related data is together.Barmar– Barmar2019年03月21日 16:37:52 +00:00Commented Mar 21, 2019 at 16:37
1 Answer 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)
answered Mar 21, 2019 at 16:41
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Biu
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...
Barmar
Why don't you want them? Your code appends them to
date_array and time_array.Biu
So I cannot use this way to generate a dictionary that only contains the items then?
Barmar
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.
lang-py