0

Having a dataframe as

  col
1   1
2   2
3   3

and another dataframe where i need to put calculated values from the previous df. the val column is a multiplication of values by index

i   j   val
1   1    1
1   2    2
1   3    3
2   1    2
2   2    4
2   3    6
3   1    3
3   2    6
3   3    9

ive tried to calculate it as using a loop but i dont think this approach is the fastest one. How can i accomplish this in a more efficient way?

2
  • Do you want the first dataframe to create the combination of i and j? Commented Apr 26, 2019 at 16:17
  • @ResidentSleeper yes the first DF should get the values for the second df Commented Apr 26, 2019 at 16:18

2 Answers 2

1

IIUC.

df2 = pd.DataFrame(index=pd.MultiIndex.from_product([df.index, df.col])).reset_index()
df2.columns = ['i', 'j']
df2['val'] = df2.i * df2.j

df2
Out[45]: 
   i  j  val
0  1  1    1
1  1  2    2
2  1  3    3
3  2  1    2
4  2  2    4
5  2  3    6
6  3  1    3
7  3  2    6
8  3  3    9
Sign up to request clarification or add additional context in comments.

Comments

0

I would suggest:

 df2['i'] = df.index
 df2['j'] = df.col
 df2['val'] = df2['j'] * df2['i']

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.