2

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

2
  • Does num column have repeated values? Commented Jul 29, 2020 at 13:37
  • no, in my complete problem it goes from 0 to 14 Commented Jul 29, 2020 at 13:39

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

You could use the following:

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

Comments

0

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']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.