aaa905
aaa905

Reputation: 55

Add to Values in An Array in a CSV File

I imported my CSV File and made the data into an array. Now I was wondering, what can I do so that I'm able to print a specific value in the array? For instance if I wanted the value in the 2nd row, 2nd column. Also how would I go about adding the two values together? Thanks.

import csv
import numpy as np
f = open("Test.csv")
csv_f = csv.reader(f)
for row in csv_f:
    print(np.array(row))
f.close()

Upvotes: 0

Views: 1437

Answers (3)

Daniel
Daniel

Reputation: 2469

To get specific values within your array/file, and add together:

import csv

f = open("Test.csv")
csv_f = list(csv.reader(f))

#returns the value in the second row, second column of your file
print csv_f[1][1]

#returns sum of two specific values (in this example, value of second row, second column and value of first row, first column
sum = int(csv_f[1][1]) + int(csv_f[0][0])
print sum

Upvotes: 0

Andrew
Andrew

Reputation: 511

So, I grabbed a dataset ("Company Funding Records") from here. Then, I just rewrote a little...

#!/usr/bin/python

import csv
#import numpy as np

csvaslist = []

f = open("TechCrunchcontinentalUSA.csv")
csv_f = csv.reader(f)
for row in csv_f:
#    print(np.array(row))
    csvaslist.append(row)
f.close()

#  Now your data is in a dict.  Everything past this point is just playing
#  Add together a couple of arbitrary values...
print int(csvaslist[2][7]) + int(csvaslist[11][7])

#  Add using a conditional...
print "\nNow let's see what Facebook has received..."
fbsum = 0
for sublist in csvaslist:
    if sublist[0] == "facebook":
        print sublist
        fbsum += int(sublist[7])
print "Facebook has received", fbsum

I've commented lines at a couple points to show what's being used and what was unneeded. Notice at the end that referring to a particular datapoint is simply a matter of referencing what is, effectively, original_csv_file[line_number][field_on_that_line], and then recasting as int, float, whatever you need. This is because the csv file has been changed to a list of lists.

Upvotes: 0

Hannes Karppila
Hannes Karppila

Reputation: 988

There is no need to use csv module.

This code reads csv file and prints value of cell in second row and second column. I am assuming that fields are separated by commas.

with open("Test.csv") as fo:
    table = [row.split(",") for row in fo.read().replace("\r", "").split("\n")]
print table[1][1]

Upvotes: 1

Related Questions