I've recently started using Python (and have also started looking at R).I came across an interesting example (copied below for reference) in R which I wanted to try and see if I could implement in Python (without using rpy or Pandas etc.).
我最近开始使用Python(并且也开始查看R)。我在R中遇到了一个有趣的例子(在下面复制以供参考)我想尝试看看我是否可以在Python中实现(不使用rpy或Pandas)等等。)。
R code-example
R代码示例
# Goal:
# A stock is traded on 2 exchanges.
# Price data is missing at random on both exchanges owing to non-trading.
# We want to make a single price time-series utilising information
# from both exchanges. I.e., missing data for exchange 1 will
# be replaced by information for exchange 2 (if observed).
# Let's create some example data for the problem.
e1 <- runif(15) # Prices on exchange 1
e2 <- e1 + 0.05*rnorm(15) # Prices on exchange 2.
cbind(e1, e2)
# Blow away 5 points from each at random.
e1[sample(1:15, 5)] <- NA
e2[sample(1:15, 5)] <- NA
cbind(e1, e2)
# Now how do we reconstruct a time-series that tries to utilise both?
combined <- e1 # Do use the more liquid exchange here.
missing <- is.na(combined)
combined[missing] <- e2[missing] # if it's also missing, I don't care.
cbind(e1, e2, combined)
I have tried
我努力了
import numpy as np
e1=np.random.random((15,)).reshape(-1,1)
e2=e1+0.05*np.random.standard_normal(15).reshape(-1,1)
np.concatenate((e1,e2),axis=1) # cbind equivalent on two vectors
I have not managed to do the next section i.e.
我没有设法做下一节,即
# Blow away 5 points from each at random
I did try python's np.random.random_sample
command but could not get it to work at all.
I would very much appreciate your assistance please with this and the last section i.e. reconstructing the timeseries that tries to utilise both data arrays as described above.
我确实尝试过python的np.random.random_sample命令,但根本无法使用它。我非常感谢您对此以及最后一节的帮助,即重建试图利用上述数据阵列的时间序列。
1 个解决方案
#1
1
You can use the "random" package
您可以使用“随机”包
import numpy as np
import random
e1=np.random.random((15,)).reshape(-1,1)
e2=e1+0.05*np.random.standard_normal(15).reshape(-1,1)
e1[random.sample(range(e1.shape[0]), 5),:] = np.nan
e2[random.sample(range(e2.shape[0]), 5),:] = np.nan
np.concatenate((e1,e2),axis=1)
#1
1
You can use the "random" package
您可以使用“随机”包
import numpy as np
import random
e1=np.random.random((15,)).reshape(-1,1)
e2=e1+0.05*np.random.standard_normal(15).reshape(-1,1)
e1[random.sample(range(e1.shape[0]), 5),:] = np.nan
e2[random.sample(range(e2.shape[0]), 5),:] = np.nan
np.concatenate((e1,e2),axis=1)