首页 > 解决方案 > 如何从类似于 iloc 的 csv 文件中选择一系列列

问题描述

简单的问题,但我真的无法让我的代码工作。我一直在寻找答案,但很多时候它们过于复杂。

例如,我有一个 CSV 文件,其中包含 6 列。

使用 pandas 将作为一个简单的示例iloc[0:2],在这种情况下我不能使用 pandas。

文件“国籍.csv”:

  id, Color , Height , Weight , LR , Nationality, Higher_ed
  23, blue , 2.5 , 100 , L , Spanish , Yes
  24, green , 2.5 , 100 , L , Dutch , No

我只想从第 1 列到第 3 列中获取。在使用 csv 的熊猫中,与 iloc 类似的代码是什么?

nationality_dict = dict()

with open("Nationality.csv", "r") as file:
    file.readline()  
    for row in file: 
        id , Color, Height, Weight  = row.strip().split(",")
        nationality_dict[int(id)] = row[1] , row[2] , row[3]

标签: pythoncsv

解决方案


如果你可以使用 csv 模块试试这个代码,我实际上并不认为有一个“超级”简单的方法可以做到这一点。这是我想出的:

import csv

with open('./Desktop/funky.csv', 'r') as f:
    for line in f:
        items = line.split(',')
        first_item = items[0] # header

    num_columns = len(items) # access number of columns
    f.seek(0) # change f's position back to 0

    reader = csv.reader(f, delimiter = ',')
    included_cols = [0,1,2] # columns you want to select (1-3)
    for row in reader: # print content in included cols
            content = list(row[i] for i in included_cols)
            print(content)

输出:

[' id', ' Color ', ' Height ']
['23', ' blue ', '2.5']
['24', ' green ', '2.5']

推荐阅读