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.
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 , row , row
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 # 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']