Use min when passing the number to the pattern. Consider a df data block
df = pd.DataFrame(dict( A=[1, 1, 1, 2, 2, 2, 2, 3, 4, 4], B=range(10) )) df.groupby('A', group_keys=False).apply(lambda x: x.sample(min(len(x), 2))) AB 1 1 1 2 1 2 3 2 3 6 2 6 7 3 7 9 4 9 8 4 8
source share