# Apply dependent double qcut (à la Fama-French) in python

Dear StackOverflow community,

I want to iterate a double qcut function, to create a dependent double sorting procedure. This procedure is employed by Fama & French (1993) to form quintiles portfolios by size then Book-Market (2criterions).

So far I only have managed to create a independent sorting procedure, by using groupie() and qcut(), in the following way by using twice this code:

['rank'] = ret.groupby('fyear')[criterion].transform(lambda x: pd.qcut(x, nport, labels=False, duplicates='drop'))

ret['rank1'] = ret.groupby('fyear')[criterion2].transform(lambda x: pd.qcut(x, nport, labels=False, duplicates='drop'))



However I want to do it in a dependent way, meaning that for each rank I want a qcut(). To create something like this:

ret['rank'] = ret.groupby('fyear')[criterion].transform(lambda x: pd.qcut(x, nport, labels=False, duplicates='drop'))

grouped=df.groupby('rank')
for i in grouped:
ret['rank2']=ret.groupby('fyear')[criterion2].transform(lambda x: pd.cut(x, nport, labels=False,duplicates='drop'))


Without luck.

Also, the following code, gives me a error message:

ret['rank2']=ret.groupby(['fyear', 'rank'])[criterion2].transform(lambda x: pd.cut(x, nport, labels=False,duplicates='drop'))


ValueError: Length mismatch: Expected axis has 133598 elements, new values have 134236 elements

Any ideas?

• there may be more responses if posted in stackoverflow Jan 18 at 10:05