Python:使用Excel CSV文件只读取特定的列和行

虽然我可以阅读CSV文件,而不是阅读整个文件如何才能打印只有特定的行和列?

想象一下,如果这是Excel:

ABCDE State |Heart Disease Rate| Stroke Death Rate | HIV Diagnosis Rate |Teen Birth Rate Alabama 235.5 54.5 16.7 18.01 Alaska 147.9 44.3 3.2 N/A Arizona 152.5 32.7 11.9 N/A Arkansas 221.8 57.4 10.2 N/A California 177.9 42.2 N/AN/A Colorado 145.3 39 8.4 9.25 

下面是我拥有的:

 import csv try: risk = open('riskfactors.csv', 'r', encoding="windows-1252").read() #find the file except: while risk != "riskfactors.csv": # if the file cant be found if there is an error print("Could not open", risk, "file") risk = input("\nPlease try to open file again: ") else: with open("riskfactors.csv") as f: reader = csv.reader(f, delimiter=' ', quotechar='|') data = [] for row in reader:# Number of rows including the death rates for col in (2,4): # The columns I want read B and D data.append(row) data.append(col) for item in data: print(item) #print the rows and columns 

我只需要阅读所有统计数据的B和D列就可以这样读取:

  ABD State |Heart Disease Rate| HIV Diagnosis Rate | Alabama 235.5 16.7 Alaska 147.9 3.2 Arizona 152.5 11.9 Arkansas 221.8 10.2 California 177.9 N/A Colorado 145.3 8.4 

编辑

没有错误

任何想法如何解决这个问题? 我所尝试的一切都不起作用。 任何帮助或build议非常感谢。

如果你仍然陷入困境,你完全没有必要用CSV模块读取文件,因为所有的CSV文件都是逗号分隔的string。 所以,对于简单的事情你可以尝试一下,这会给你一个forms(状态,心脏病发病率,HIV诊断率)

 output = [] f = open( 'riskfactors.csv', 'rU' ) #open the file in read universal mode for line in f: cells = line.split( "," ) output.append( ( cells[ 0 ], cells[ 1 ], cells[ 3 ] ) ) #since we want the first, second and third column f.close() print output 

请注意,如果您想进行任何types的数据分析,则必须经过并忽略标题行。

我希望你已经听说了pandas的数据分析。

下面的代码将完成读取列的工作,但是读取行可能需要解释更多。

 import pandas io = pandas.read_csv('test.csv',sep=",",usecols=(1,2,4)) # To read 1st,2nd and 4th columns print io 

尝试这个

 data = [] for row in reader:# Number of rows including the death rates data.append([row[1],row[3]) # The columns I want read B and D for item in data print(item) #print the rows and columns