I'm trying to loop through a list and a data frame where if the id in the list is equal to the id in the data frame, do something to that row in the data frame.
import pandas as pd
data = [['a1','Alex',10],['a1','Bob',12],['a1','Clarke',13],['a2','den',14],['a2','emry',15]]
df = pd.DataFrame(data,columns=['id','Name','Age'])
unique_ids = ['a1','a2']
First loop through the list. If the id in the data frame == the id in the unique_ids list, then do the below:
- If the unique id in the next row is still the same as the row before, then set the second argument to be the last value from the row above. So, since
12is the last item in the first row anda1is still the same id as above, set 12 to be the second value in the second row.
For example: expected output from the input above would be
a1,10,12
a1,12,13
a2,14,15
How I tried to do it:
for i in unique_ids:
for row in df.itertuples(index=True, name='Pandas'):
while i == getattr(row,"id"):
print (getattr(row,"id"),getattr(row,"age")
not sure how to proceed as im getting stuck at the while loop