How to select a range of columns from a csv file similar to iloc

3970 views python
3

Simple question but I really can't get my code to work. I have searched for answers but a lot of the times they are overcomplicated.

For example I have a CSV file that has let say 6 columns.

Using pandas would be as an example a simple iloc[0:2], in this case I cannot use pandas.

File "Nationality.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

I want to get only from column 1 to 3.. What is a similar code to iloc in pandas using csv?

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]

answered question

Why not use .iloc itself?

@DYZ cant use pandas:(

Please make it clear in the question.

@edited , sorry.

A csv.DictReader is what you need.

@how do you select in csv.Dictreader?

Reading the documentation would be a great starting point.

1 Answer

4

If you can use the csv module try this code out, I don't actually think there is a "super" easy way to do this with out pandas. Here is what I came up with:

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)

output:

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

posted this

Have an answer?

JD

Please login first before posting an answer.