I have a csv file that looks like this:
Names, Size, State, time1, time2,
S1, 22, MD , 0.022, , 523.324
S2, 22, MD , 4.32, , 342.54
S3, 22, MD , 3.54, , 0.32
S4, 22, MD , 4.32, , 0.54
S1, 33, MD , 5.32, , 0.43
S2, 33, MD , 11.54, , 0.65
S3, 33, MD , 22.5, , 0.324
S4, 33, MD , 45.89 , 0.32
S1, 44, MD , 3.53 , 3.32
S2, 44, MD , 4.5 , 0.322
S3, 44, MD , 43.65 , 45.78
S4, 44, MD, 43.54 , 0.321
Here is my code to reformat the data:
import csv
with open(r'C:\Users\testuser\Desktop\raw_inpuy.csv.csv','rb') as csvfile:
reader=csv.reader(csvfile, delimiter=',')
first=True
data={}
column= input("What column do you want to see: (x,y,z)")
for row in reader:
size = int(row[1])
column = float(row[3]) # the problem lies here. I know that the column header plus row # must match but I do not know how to code it
if not size in data:
data[size] = []
data[size].append(column)
writer = csv.writer(sys.stdout)
writer.writerow(["Size", "S1", "S2", "S3", "S4"])
for item in data:
row = [item]
row.extend(data[item])
writer.writerow(row)
It outputs this to the csv:
Size,S1,S2,S3,S4
33,5.32,11.54,22.5,45.89
44,3.53,4.5,43.65,43.54
22,0.022,4.32,3.54,4.32
This is correct but it only displays the time1 column but I want to be able to also see the time2 column if I ask for it. There is also a time3 column that I did not include Even though I asked for the user input and declared it as a variable it still only prints the time1 column even if I ask for the time2 column.
input("What column do you want to see: (x,y,z)")- instead you overwritecolumn.time2would be inrow[4]of thecsv.reader.col_nr = int(input(...))and thencolumn = float(row[col_nr])?