1

I have two pandas series a and b as follows:

a = pd.series([1, 2, 3])

b = pd.series([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

What I want to get is a third pandas series as follows:

[[1, 2, 3], [8, 10, 12], [21, 24, 27]]

I have tried the following operations:

a*b

np.array(a)*np.array(b)

np.multiple(a, b)

a.multiple(b)

However, I keep getting the same error as follows:

TypeError: can't multiply sequence by non-int of type 'float'

I wonder what's the right way to do this? Thanks!

Thientvse
  • 1,753
  • 1
  • 14
  • 23
CathyQian
  • 1,081
  • 15
  • 30

1 Answers1

1

Use numpy broadcasting, docs:

c = np.array(b.values.tolist()) * a[:,np.newaxis])
[[ 1  2  3]
 [ 8 10 12]
 [21 24 27]]

Or:

c = np.array(b.values.tolist()) * a.values.reshape(len(a),-1)
print (c)
[[ 1  2  3]
 [ 8 10 12]
 [21 24 27]]

And then:

s3 = pd.Series(c.tolist())
print (s3)
0       [1, 2, 3]
1     [8, 10, 12]
2    [21, 24, 27]
dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • It works! Thanks a lot! Can you help me understand why my code doesn't work? – CathyQian Nov 10 '17 at 06:58
  • I think you cannot use `a.mul(b)`, because in pandas is not implemented multiple in lists. Need create 2d numpy array with lists and then here the `newaxis` index operator inserts a new `axis` into a, making it a two-dimensional `3x1 array`. – jezrael Nov 10 '17 at 07:03
  • Yea it makes sense! Thanks again! – CathyQian Nov 10 '17 at 07:07