我导入了我的CSV文件并将数据转换为数组。现在我想知道,我能做什么才能在阵列中打印特定的值?例如,如果我想要第2行,第2列中的值。 另外,我将如何将两个值一起添加?感谢。
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()
答案 0 :(得分:1)
无需使用csv模块。
此代码读取csv文件并在第二行和第二列中打印单元格的值。我假设字段用逗号分隔。
with open("Test.csv") as fo:
table = [row.split(",") for row in fo.read().replace("\r", "").split("\n")]
print table[1][1]
答案 1 :(得分:0)
所以,我从here抓取了一个数据集("公司资金记录")。然后,我只是重写了一点......
#!/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
我在几个点上评论了一些线条,以显示正在使用的内容和不需要的内容。最后请注意,引用一个特定的数据点只是引用什么是有效的original_csv_file [line_number] [field_on_that_line],然后重铸为int,float,无论你需要什么。这是因为csv文件已更改为列表列表。
答案 2 :(得分:0)
要获取数组/文件中的特定值,并将它们加在一起:
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