Prasad Prasad - 10 months ago 48
Python Question

Python for loop over two lists for all the pairs

I have a dataframe with date, id - I need to pull out each date and id combination and create a new dataframe.

date id
2016-05-13 abc
2016-05-13 pqr
2016-05-14 abc
2016-05-14 pqr

ids = list(sorted(set(df['id'])))
Out: ['abc','pqr']

dates = list(sorted(set(df[ == ids[i]]['date'])))
Out: ['2016-05-13','2016-05-14']

for i in range(0,len(ids)):
df2 = df[( == dates[i]) & ( == id[i])]

The above code is resulting the output (
) for relative index values only (First date, First Id & Second date, Second Id), but I need the output for all the pairs. Please let me know what to change in the loop?

Answer Source

to get all the pairs ids vs. dates, you could use itertools as

import itertools

for iid, ddate in itertools.product(ids, dates):
    df2 = df[( == ddate) & ( == iid)]