简体   繁体   中英

Vlook up in Python using a for loop

I have been trying to build vlookup function in python. I have two files. name = data - created in pythong which has more than 2000 rows. comp_data = csv file loaded in system which has 35 rows. I have to match date of data file with comp_data and have to load Exp_date corresponding to it. Current code gives error '35'. I am not able to understand the problem. Please help. Following are the codes:

data['Exp_date'] = datetime.date(2020,3,30)
z=0
for i in range(len(data)):
    if data['Date'][i] == comp_data['Date'][z]:
        data['Exp_date'][i] = comp_data['Exp_date'][z]
    else:
        z=z+1

One option would be to put your comp_data in a dictionary with your data/exp_date as key/value pairs and let python do the lookup for you.

data = {"date":["a","b","c","d","e","f"],"exp_date":[0,0,0,0,0,0]}
comp = {"a":10,"d":13}

for i in range(len(data['date'])):
    if data['date'][i] in comp:
        data['exp_date'][i] = comp[data['date'][i]]
print(data)

There's probably a one-liner way of doing this with iterators!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM