beyond_acm
beyond_acm

Reputation: 37

pandas multiply between dataframe and series(column)

For example, I have a dataframe like

[ 2 2 2
  3 3 3 
  4 4 4
  5 5 5] 

and I have a serise [2 1 2 1] How can I get the

[ 4 4 4
  3 3 3
  8 8 8
  5 5 5]

?

Upvotes: 2

Views: 1545

Answers (2)

Anton Protopopov
Anton Protopopov

Reputation: 31672

You could do that using numpy broadcasting:

In [36]: df.values
Out[36]:
array([[2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5]], dtype=int64)

In [37]: s.values
Out[37]: array([2, 1, 2, 1], dtype=int64)

In [38]: df.values * s.values[:,None]
Out[38]:
array([[4, 4, 4],
       [3, 3, 3],
       [8, 8, 8],
       [5, 5, 5]], dtype=int64)

Timing:

In [44]: %timeit df.mul(s, axis=0)
1000 loops, best of 3: 197 us per loop

In [45]: %timeit df.mul(s, axis=0).values
1000 loops, best of 3: 210 us per loop

In [46]: %timeit df.values * s.values[:,None]
100000 loops, best of 3: 16.4 us per loop

In [48]: %timeit pd.DataFrame(df.values * s.values[:,None])
10000 loops, best of 3: 164 us per loop

Upvotes: 1

jezrael
jezrael

Reputation: 862661

You can try mul and if you need convert DataFrame to numpy array use values:

print df
   0  1  2
0  2  2  2
1  3  3  3
2  4  4  4
3  5  5  5

s = pd.Series([2, 1, 2, 1])
print s
0    2
1    1
2    2
3    1
dtype: int64

print df.mul(s, axis=0)
   0  1  2
0  4  4  4
1  3  3  3
2  8  8  8
3  5  5  5

print df.mul(s, axis=0).values
[[4 4 4]
 [3 3 3]
 [8 8 8]
 [5 5 5]]

Upvotes: 2

Related Questions