Home > other >  Multiply numpy to dataframe where index number in numpy matches the dataframe value
Multiply numpy to dataframe where index number in numpy matches the dataframe value

Time:10-22

I would like to multiply values in a numpy array to a column in pandas dataframe where the index of the numpy array matches the values in a pandas dataframe.

For example, I have a dataframe and a numpy array like this.

data = {'v_index': [0, 1, 2, 3, 4, 0, 4, 3], 'values': [5, 5, 10, 10, 20,20,10,10]}  
pd.DataFrame(data)

v_index values
0   0   5
1   1   5
2   2   10
3   3   10
4   4   20
5   0   20
6   4   10
7   3   10

np.array([1,3,5,7,9])

Now I want to match the index of numpy array to values in column "v_index" and multiply their values. My desired output looks like this.

v_index values
0   0   5 -> 5*1 = 5
1   1   5 -> 5*3 = 15
2   2   10 -> 10*5 = 50
3   3   10 -> 10*7 = 70
4   4   20 -> 20*9 = 180
5   0   20 -> 20*1 = 20
6   4   10 -> 10*9 =90
7   3   10 -> 10*7 =70

Can someone help me figure this out?

CodePudding user response:

Try

df['values'] *= arr[df['v_index']]

Output:

   v_index  values
0        0       5
1        1      15
2        2      50
3        3      70
4        4     180
5        0      20
6        4      90
7        3      70
  • Related