虽然我可以读取csv文件而不是读取整个文件,但如何只打印某些行和列?
想象一下,好像这是Excel:
A B C D E
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/A N/A
Colorado 145.3 39 8.4 9.25
Run Code Online (Sandbox Code Playgroud)
继承人我所拥有的:
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
Run Code Online (Sandbox Code Playgroud)
我只需要读取列B和D,所有统计信息都是这样读的:
A B D
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
Run Code Online (Sandbox Code Playgroud)
没有错误
关于如何解决这个问题的任何想法?我尝试的一切都不起作用.非常感谢任何帮助或建议.
Lon*_*oul 10
我希望你听说过Pandas for Data Analysis.
以下代码将执行读取列的工作,但是有关读取行的信息,您可能需要解释更多.
import pandas
io = pandas.read_csv('test.csv',sep=",",usecols=(1,2,4)) # To read 1st,2nd and 4th columns
print io
Run Code Online (Sandbox Code Playgroud)