簡體   English   中英

使用Python讀取csv文件的第i列的最佳方法是什么?

[英]What is the best way to read the ith column of a csv file with Python?

我已經習慣了R,它提供了快速的功能來逐列讀取CSV文件,有人可以提出一種快速有效的方法來讀取python中的大數據(例如CSV)文件嗎? 例如,CSV文件的 i列。

我有以下但需要時間:

    import os,csv, numpy, scipy
    from numpy import *
    f= open('some.csv', 'rb') 
    reader = csv.reader(f, delimiter=',')
    header = reader.next()
    zipped = zip(*reader)
    print( zipped[0] ) # is the first column

有沒有更好的方法來讀取python中的數據(從大文件)(至少在內存方面與R一樣快)?

您還可以使用pandas.read_csv及其use_cols參數。 看到這里

import pandas as pd

data = pd.read_csv('some.csv', use_cols = ['col_1', 'col_2', 'col_4'])
...
import csv

with open('some.csv') as fin:
    reader = csv.reader(fin)
    first_col = [row[0] for row in reader]

您使用zip所做的就是將整個文件加載到內存中,然后將其轉置以獲取col。 如果只需要列值,則只需在列表中包括該值即可。

如果需要多個列,則可以執行以下操作:

from operator import itemgetter
get_cols = itemgetter(1, 3, 5)
cols = map(get_cols, reader)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM