简体   繁体   中英

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

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)
>>> np.outer(a, ts)
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM