如何从csv文件读取前两列

时间:2019-01-04 11:28:31

标签: python csv

我的任务是使用python读取csv文件。

任务是从csv文件中读取前两列。

csv文件外观

car name,miles/gallon,cylinders,displacement,horsepower,weight,acceleration,model year,origin
"chevrolet chevelle malibu",18,8,307,130,3504,12,70,1
"buick skylark 320",15,8,350,165,3693,11.5,70,1
"plymouth satellite",18,8,318,150,3436,11,70,1

我的代码:

import csv
list2 = []
with open("mylist.csv") as f:
    for row in f:
        list2.append(row[0])

3 个答案:

答案 0 :(得分:0)

要阅读前两列,请使用切片来附加列表而不是标量。由于您使用的是csv模块,因此可以使用csv.reader来简化逻辑:

import csv
from io import StringIO

x = '''car name,miles/gallon,cylinders,displacement,horsepower,weight,acceleration,model year,origin
"chevrolet chevelle malibu",18,8,307,130,3504,12,70,1
"buick skylark 320",15,8,350,165,3693,11.5,70,1
"plymouth satellite",18,8,318,150,3436,11,70,1'''

list2 = []
# replace StringIO(x) with open('mylist.csv', 'r')
with StringIO(x) as fin:
    reader = csv.reader(fin)
    headers = next(reader)[:2]
    for row in reader:
        list2.append(row[:2])

print(headers, list2, sep='\n')

# ['car name', 'miles/gallon']
# [['chevrolet chevelle malibu', '18'], ['buick skylark 320', '15'], ['plymouth satellite', '18']]

要将第二列读取为整数,可以修改逻辑:

list2.append([row[0], int(row[1])])

答案 1 :(得分:0)

您可以这样尝试熊猫-

import os
import pandas as pd
filename = os.path.dirname(__file__)+'/mylist.csv'
df = pd.read_csv(filename, header=1, index_col=None, names=['car name','miles/gallon','cylinders','displacement','horsepower','weight','acceleration','model year','origin'])
df = df[['car name','miles/gallon']]
print(df)

答案 2 :(得分:0)

熊猫 read_csv()具有内置功能,可以指定要读取文件的哪些列。只需为usecols提供单个整数值或列索引列表即可:

import pandas as pd
df = pd.read_csv('~/file.csv', usecols=[0,1], header=0)
print(df)

输出:

                    car name  miles/gallon
0  chevrolet chevelle malibu            18
1          buick skylark 320            15
2         plymouth satellite            18