python - How to multiply pandas dataframes and preserve row keys -
i'm struggling multiplying dataframes , preserving row keys.
i have 2 files, call them f1 , f2. f1 has multi-part group key (g1,g2,g3), two-part type key (k1,k2) , weights (r1,r2). f2 has series of values each type key.
i'd join them on k1 , k2, , multiply r1 , r2 each n.
i'm thinking groupby , dataframe multiply should work can't see how it. thing i've got work merge , multiply column column, it's super-slow.
f1 g1 g2 g3 k1 k2 r1 r2 1 2 b 3 4 b b 2 3 f2 k1 k2 n r1 r2 1 0 1 2 1 1 3 1 0 b 1 3 4 b 2 4 4 b 3 4 3 c 1 1 1 c 3 4 5 c 2 3 4 result g1 g2 g3 k1 k2 n r1 r2 1 0 2 2 1 2 3 1 0 b 1 9 16 b 2 12 16 b 3 12 12 b b 1 6 12 b b 2 8 12 b b 3 8 9
thanks
mrg = f1.merge(f2, on=['k1', 'k2']) mrg['r1'] = mrg.filter(like='r1').prod(1) mrg['r2'] = mrg.filter(like='r2').prod(1) drops = ['r1_x', 'r1_y', 'r2_x', 'r2_y'] mrg.drop(drops, axis=1)
Comments
Post a Comment