CathyQian
CathyQian

Reputation: 1159

pandas series elementwise muplication

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!

Upvotes: 1

Views: 495

Answers (1)

jezrael
jezrael

Reputation: 862851

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

Upvotes: 1

Related Questions