![](/img/trans.png)
[英]WITHOUT using Pandas, how do I analyze CSV data and only extract certain values from certain columns and rows of my CSV file?
[英]How to get specific columns in a certain range from a csv file without using pandas
由於某種原因,pandas模塊不起作用,我必須找到另一種方式來讀取(大)csv文件,並在一定范圍內(例如前1000行)使用特定於輸出的列。 我有讀取整個csv文件的代碼,但是我還沒有找到只顯示特定列的方法。
任何幫助深表感謝!
import csv
fileObj = open('apartment-data-all-4-xaver.2018.csv')
csvReader = csv.reader( fileObj )
for row in csvReader:
print row
fileObj.close()
使用csv dictreader,然后過濾掉特定的行和列
import csv
data = []
with open('names.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
colnames = ['col1', 'col2']
for i in range(1000):
print(data[i][colnames[0]], data[i][colnames[1]])
我創建了一個包含以下內容的小型csv文件:
first,second,third
11,12,13
21,22,23
31,32,33
41,42,43
您可以使用以下幫助程序函數,該函數使用來自collections模塊的namedtuple,並生成允許您訪問諸如屬性之類的列的對象:
import csv
from collections import namedtuple
def get_first_n_lines(file_name, n):
with open(file_name) as file_obj:
csv_reader = csv.reader(file_obj)
header = next(csv_reader)
Tuple = namedtuple('Tuple', header)
for i, row in enumerate(csv_reader, start=1):
yield Tuple(*row)
if i >= n: break
如果要打印第一行和第三列,每行n = 3行,請使用以下方法(Python 3.6 +):
for line in get_first_n_lines(file_name='csv_file.csv', n=3):
print(f'{line.first}, {line.third}')
或像這樣(Python 3.0-3.5):
for line in get_first_n_lines(file_name='csv_file.csv', n=3):
print('{}, {}'.format(line.first, line.third))
輸出:
11, 13
21, 23
31, 33
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.