1

I need a small help....

Csv file sample :

ID, name, age, city1,city2,city3
1, Andy, 25, "Ann Arbor,NA","CA,NA","MS,NA"
2, Bella, 40, "Los Angeles,NA"
3, Cathy, 13, "Eureka,NA","NV,NA"

My current code :

name=[]
age=[]
with open ('File_name','r') as f:
   reader=DictReader(f)
   for row in reader:
     name.append(row['name'])#append all names
     age.append(row['age'])

Now i need to print the cities.There is no certainity that will lived in only 3 cities.While updating data source,there might be more cities....So what i think is Creating a variables by loop .

Method i tried : Our Column is 3...there is no changes in it..

ID=2 #user requirement
name=[]
age=[]
cities=[]
with open ('File_name','r') as f:
   reader=DictReader(f)
   for row in reader:
    if ID == row['ID']:
     name.append(row['name'])#append all names
     age.append(row['age'])
     Def_Fil=len(row)-3
     for i in range(Def_Fil):
        city=city.append(row['city+str(i)']) #I dont aware how to declare the row name,i need to iterate manually...i can print name and age...but here depend number of cities i need to declare.
    print(name,age,city)

But am facing "SyntaxError: cannot assign to operator"

My expected output:

when i print city of ID 3 : ["Eureka,NA","NV,NA"] ID 2 : ["Los Angeles,NA"] ID 1 : ["Ann Arbor,NA","CA,NA","MS,NA"]

Stay cool
  • 11
  • 6

1 Answers1

0

If you are not forced to use DictReader you can use pandas instead:

import pandas as pd

csv = pd.read_csv('data.csv', delimiter=',', skipinitialspace=True)

def getCities(ID):
    # get the row with the given ID
    row = csv[csv['ID'] == ID]
    # get the cities columns (all columns but the first 3 'ID, name, age')
    cities = row.iloc[:, 3:].values.tolist()[0]
    # convert to a list of strings remove nan values
    re = [str(x) for x in cities if str(x) != 'nan']
    return re

print(getCities(3))
print(getCities(2))
print(getCities(1))

This gives you:

['Eureka,NA', 'NV,NA']
['Los Angeles,NA']
['Ann Arbor,NA', 'CA,NA', 'MS,NA']

Your dataframe looks like this:

print(csv)
   ID   name  age           city1  city2  city3
0   1   Andy   25    Ann Arbor,NA  CA,NA  MS,NA
1   2  Bella   40  Los Angeles,NA    NaN    NaN
2   3  Cathy   13       Eureka,NA  NV,NA    NaN

If you want to access all ages or names:

print(csv['age'].values.tolist())
print(csv['name'].values.tolist())
[25, 40, 13]
['Andy', 'Bella', 'Cathy']

If you want to get the age of a person with a specific ID or Name

print(csv[csv['ID'] == 1]['age'].values.tolist()[0])
print(csv[csv['name'] == 'Bella']['age'].values.tolist()[0])
25
40
noah1400
  • 1,282
  • 1
  • 4
  • 15