zsljulius
zsljulius

Reputation: 4103

numpy array elementwise multiply a panda timeseries

I have these two data structures:

a = np.array([1,2,3])
ts = pd.TimeSeries([1,2,3])

What I want to get at the end is:

1  2  3
2  4  6
3  6  9

Upvotes: 3

Views: 114

Answers (2)

askewchan
askewchan

Reputation: 46530

You can use the outer product:

In [490]: np.outer(a, ts)
Out[490]: 
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Or align one of them vertically first:

In [491]: a * ts[:, None]
Out[491]: 
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Note that the strange index just makes it a column vector:

In [493]: ts[:, None]
Out[493]: 
array([[1],
       [2],
       [3]])

by adding an extra length-1 dimension to the shape:

In [494]: ts[:, None].shape
Out[494]: (3, 1)

Upvotes: 5

Jake Burkhead
Jake Burkhead

Reputation: 6535

>>> np.outer(a, ts)
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

Upvotes: 4

Related Questions