我试图通过csv文件进行解析,并仅从特定列中提取数据。

例csv:

ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

我试图只捕获特定的列,比如ID、Name、Zip和Phone。

我看过的代码让我相信我可以通过对应的数字调用特定的列,因此ie: Name将对应于2,并且使用行[2]遍历每一行将产生列2中的所有项。但事实并非如此。

以下是我目前所做的:

import sys, argparse, csv
from settings import *

# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
 fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file

# open csv file
with open(csv_file, 'rb') as csvfile:

    # get number of columns
    for line in csvfile.readlines():
        array = line.split(',')
        first_item = array[0]

    num_columns = len(array)
    csvfile.seek(0)

    reader = csv.reader(csvfile, delimiter=' ')
        included_cols = [1, 2, 6, 7]

    for row in reader:
            content = list(row[i] for i in included_cols)
            print content

我期望它只打印出每行我想要的特定列,但它没有,我只打印出最后一列。


当前回答

对于pandas,你可以使用read_csv和usecols参数:

df = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

例子:

import pandas as pd
import io

s = '''
total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
'''

df = pd.read_csv(io.StringIO(s), usecols=['total_bill', 'day', 'size'])
print(df)

   total_bill  day  size
0       16.99  Sun     2
1       10.34  Sun     3
2       21.01  Sun     3

其他回答

由于你可以索引和子集pandas数据框架,一个非常简单的方法从csv文件提取单列到一个变量是:

myVar = pd.read_csv('YourPath', sep = ",")['ColumnName']

有几件事需要考虑:

上面的代码片段将生成一个pandas系列,而不是数据框架。 如果速度是一个问题,ayhan和usecols的建议也会更快。 在一个2122 KB大小的csv文件上使用%timeit测试这两种不同的方法,usecols方法得到22.8 ms的结果,而我建议的方法得到53 ms的结果。

别忘了进口熊猫当pd

使用熊猫:

import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']

在解析时丢弃不需要的列:

my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

附注:我只是以一种简单的方式汇总其他人说过的话。实际答案是从这里和这里取的。

要获取列名,最好使用readline()而不是readlines(),以避免循环&读取完整文件并将其存储在数组中。

with open(csv_file, 'rb') as csvfile:

    # get number of columns

    line = csvfile.readline()

    first_item = line.split(',')
import pandas as pd

dataset = pd.read_csv('Train.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values

X是一堆列,如果你想读更多的列,就用它 Y是单列,用它来读一列 [:, 1:-1]是[row_index: to_row_index, column_index: to_column_index]

SAMPLE.CSV
a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
print(df)
OUTPUT
  Letter  Number Symbol
0      a       1      +
1      b       2      -
2      c       3      *
3      d       4      /

letters = df.Letter.to_list()
print(letters)
OUTPUT
['a', 'b', 'c', 'd']