Home > Net >  Storing all the values in column of a CSV file to a variable
Storing all the values in column of a CSV file to a variable

Time:12-06

I have read the values from the Items.csv file and stored them in the dictionary items. I want to extract the values of C1 in the CSV file and assign them to a variable c1 for mathematical calculations. However, when I try to do it the following way, it just stores all the values in index [0] of the items[keys] rather than the whole column of C1. What am I doing wrong here? Thank you in advance.

import csv


file = open('Items.csv', encoding='utf-8-sig')
reader = csv.reader(file, delimiter=',')
items = dict()
headersRead = False
headers = []

for row in reader:
    if headersRead == False:
        for i in range(len(row)):
            items[row[i]] = []

        headers = row
        headersRead = True

    else:
        for i in range(len(row)):
            items[headers[i]].append(row[i])

for key in items:
    if key == 'Item':
        continue
    c1 = float(items[key][0])
    c2 = float(items[key][1])
    c3 = float(items[key][2])
    constant = float(items[key][3])

This is the CSV file I am working with.

Item,C1,C2,C3,Constant
Guitar Hero,-0.1111,0,-0.2,10
iPhone 7,-0.1,-0.2,-0.33333,3
iPhone SE,-0.889,-0.23,-0.5,2
Star Wars,-0.0778,-0.373333333,-0.5,4
Markers,-0.667,-0.488333333,-0.65,3
Avengers,-0.556,-0.603333333,-0.756667,5
Elf on the Shelf,-0.04,-0.718333333,-0.863334,1
Pool Cue,-0.334,0,0,9
Tire Repair Kit,-0.223,-0.948333333,-0.076668,6
Silly Putty,-0.112,-0.063333333,-0.183335,1
Nike,-0.123,-0.178333333,0,5

I want the values for the c1 to be values of key C1 from the items dictionary read in from Items.csv file. Therefore, the values of c1 should be -0.1111, -0.1, -0.889, -0.0778, -0.667, -0.556, -0.04, -0.334, -0.223, -0.112, -0.123

CodePudding user response:

I'd use csv.DictReader to read your rows as dictionaries, then update that row to convert the floats for the numeric values and append it to a list, eg:

import csv

with open('Items.csv') as fin:
    rows = []
    csvin = csv.DictReader(fin)
    for row in csvin:
        row.update((k, float(v)) for k, v in row.items() if k != 'Item')
        rows.append(row)

rows will then be a list of dictionaries.

CodePudding user response:

Your code has all the values of C1 stored as strings in an array in the items Dict : items['C1'].

c1AsFloats = map(lambda x: float(x), items['C1']) would give you an array of floating point numbers that you could then treat mathematically.

Note that in the last for loop of your code, the variables c1, c2, c3 and constant take on the first four values of items[key]. For example, when the variable key is 'C3', the variables c1, c2, c3 and constant take on the first four values of items['C3'] : c1 = '10', c2 = '3', c3 = '2' and constant = '4'.

CodePudding user response:

If your end goal is to store the values in C1 to a variable for calculation, you can access that using your dictionary items

items = {'Item': [], 'C1' : [], 'C2' : [], 'C3' : [], 'Constant' : []}
import csv
with open('Items.csv') as f:
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
      items['Item'].append(row[0])
      items['C1'].append(float(row[1])) 
      items['C2'].append(float(row[2]))
      items['C3'].append(float(row[3]))
      items['Constant'].append(float(row[4]))
print(items['C1']) #the variable that would hold the C1

which will give the output that you expect

['-0.1111', '-0.1', '-0.889', '-0.0778', '-0.667', '-0.556', '-0.04', '-0.334', '-0.223', '-0.112', '-0.123']
  • Related