【问题标题】:What is the best way to read the ith column of a csv file with Python?用 Python 读取 csv 文件的第 i 列的最佳方法是什么?
【发布时间】:2013-05-27 15:23:01
【问题描述】:

我习惯了 R,它提供了逐列读取 CSV 文件的快速功能,任何人都可以提出一种 快速 和有效的方法来读取 python 中的大数据(例如 CSV)文件吗?例如 CSV 文件的第 ith 列。

我有以下但需要时间:

    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 一样快)?

【问题讨论】:

    标签: python r python-2.7 csv import-from-csv


    【解决方案1】:

    您还可以使用pandas.read_csv 及其use_cols 参数。见here

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

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

        猜你喜欢
        • 2017-04-15
        • 2010-09-24
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        相关资源
        最近更新 更多