0

Assume that I have a dataframe of two rows and 13 columns. I have used df.itertuples() and formed two lists as an output

for row in test.itertuples(index = False):
    a = np.asarray(row)
    print(a)

let us assume that the Output of the above loop is

Output : [1,2,3,4,5,6,7,8,9,10,11,12,13]
[14,15,16,17,18,19,20,21,22,23,24,25,26]

I have one more list which is of shape (2,) test_y = [21,24]

I also tried

a = test.values.tolist()
output : array([[1,2,3,4,5,6,7,8,9,10,11,12,13],
[14,15,16,17,18,19,20,21,22,23,24,25,26]])

this forms list of lists and then multiplying test_y to a results in an error

error :operands could not be broadcast together with shapes (2,13) (2,)

The objective is multiply the list [1,2,3....] with 21 and the other with 24. or is there any way which is simpler than this

learner
  • 35
  • 8

3 Answers3

1

Since you have already converted a to a list, you can use numpy

import numpy as np
np.transpose(np.multiply(np.transpose(a),test_y))

Output:

[[ 21  42  63  84 105 126 147 168 189 210 231 252 273] 
 [336 360 384 408 432 456 480 504 528 552 576 600 624]]

If you need to sum the elements, (i.e 21+336, 42+360 and so on..) then the transpose is not required.

ans=np.multiply(np.transpose(a),test_y)

[[ 21 336]
 [ 42 360]
 [ 63 384]
 and so on...]

No just sum each of these individual lists

sum_ans=[np.sum(x) for x in ans]
#[357, 402, 447, 492, 537, 582, 627, 672, 717, 762, 807, 852, 897]
Sruthi
  • 2,908
  • 1
  • 11
  • 25
0

Since you tag pandas

df=pd.DataFrame()
df['c1']= [1,2,3,4,5,6,7,8,9,10,11,12,13] 
df['c2']=[14,15,16,17,18,19,20,21,22,23,24,25,26]
df.mul([21,24])
Out[62]: 
     c1   c2
0    21  336
1    42  360
2    63  384
3    84  408
4   105  432
5   126  456
6   147  480
7   168  504
8   189  528
9   210  552
10  231  576
11  252  600
12  273  624
BENY
  • 317,841
  • 20
  • 164
  • 234
0

You can apply a function to the DataFrame which calculates the multiplication:

In: df.apply(lambda x: x*test_y)
Out: 
    0    1    2    3    4    5    6    7    8    9    10   11   12
0   21   42   63   84  105  126  147  168  189  210  231  252  273
1  336  360  384  408  432  456  480  504  528  552  576  600  624
SpghttCd
  • 10,510
  • 2
  • 20
  • 25