I have a (really big) pandas Dataframe df:
country age gender
Brazil 10 F
USA 20 F
Brazil 10 F
USA 20 M
Brazil 10 M
USA 20 M
I have another pandas Dataframe freq:
age gender counting
10 F 0
10 M 0
20 F 0
I wanna count the pair of values in freq when they occur in df:
age gender counting
10 F 2
10 M 1
20 F 1
I'm using this code, but it takes too long:
for row in df.itertuples(index=False):
freq.loc[np.all(freq['age','gender']==row[2:3],axis=1),'counting'] += 1
Is there a faster way to do that?
Please note:
- I have to use freq because not all combinations (as for instance 20 and M) are desired
- some columns in df may not be used
- counting counts how many times both values appear in each row
- freq may have more than 2 values to check for (this is just an small example)