Multiply two columns by following a pattern using pandas

Viewed 137

I would like to multiply two columns of a df by following a specific pattern without using a loop. I have this df :

num m   d
0   8   5
1   2   3
2   17  8

The idea is to multply for each row in 'm' every row in 'd' except the one with the same 'num'. The resulting df would be :

num1 num2 mult
0    1    8x3 = 24
0    2    8x8 = 64
1    2    2x8 = 16 

Is there a way to do that ?

Thank for your help

3 Answers

You can try:

df = df.set_index('num')

((df[['m']].rename(columns={'m':'d'}) @ df[['d']].T)
   .rename_axis('num2', axis=1)
   .stack().reset_index(name='mult')
)

Or use broadcasting:

(pd.DataFrame(df['m'].values * df['d'].values[:,None],
             index=df['num'],
             columns=df['num'].rename('num2'))
   .stack().reset_index(name='mult')
)

   num  num2  mult
0    0     0    40
1    0     1    24
2    0     2    64
3    1     0    10
4    1     1     6
5    1     2    16
6    2     0    85
7    2     1    51
8    2     2   136

You could use the following:

product = df1['m'][df2['num1']].values*df1['d'][df2['num2']].values
df2['mult'] = pd.Series(product, index=df2.index)

I'd recommend first creating a frame with all possible permutations of the 2 columns, then filtering out the rows which don't correspond to the required pattern.

Something like this

df = df.set_index('num')

((df[['m']].rename(columns={'m':'d'}) @ df[['d']].T)
   .rename_axis('num2', axis=1)
   .stack().reset_index(name='mult')
)
df[df['num']!=df['num2']]
Related