Python-按左值快速插值
这是一项任务。 我有几点意见: (全部为numpy阵列) 我想对numpy数组[10001001,…10491050]进行插值。 因此,每个值都等于间隔的左侧:Python-按左值快速插值,python,performance,numpy,Python,Performance,Numpy,这是一项任务。 我有几点意见: (全部为numpy阵列) 我想对numpy数组[10001001,…10491050]进行插值。 因此,每个值都等于间隔的左侧: 1000 - (some, doesn't matter) 1001 - 0 1002 - 0 (because left - in 1001 is 0) 1003 - 0 .... 1009 - 0 1010 - 0 1011 - 0 ... 1019 - 0 1020 - 1 1021 - 1 ... 1024 - 1 1025
1000 - (some, doesn't matter)
1001 - 0
1002 - 0 (because left - in 1001 is 0)
1003 - 0
....
1009 - 0
1010 - 0
1011 - 0
...
1019 - 0
1020 - 1
1021 - 1
...
1024 - 1
1025 - 1
1026 - 1
...
1049 - 1
1050 - 1.
我不想在纯Python中这样做,因为这很慢。
我可以用numpy和scipy。没有Cython或С++,我能快速解决这个问题吗?您应该明确指定端点:
>>> x = np.array(xp+[1051])
获取长度:
>>> np.diff(x)
array([ 9, 10, 5, 26])
然后重复:
>>> np.repeat(yp, np.diff(x))
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1])
或获取二维阵列:
>>> np.vstack([np.arange(x[0], x[-1]), np.repeat(yp, np.diff(x))]).T
array([[1001, 0],
[1002, 0],
[1003, 0],
...
[1020, 1],
...
[1050, 1]])
在说Python在这方面做得很慢之前,先向我们展示一下您已经做了什么。这似乎是列表构造,Python很好地处理了它:)这并不有趣。Python循环总是比本机代码慢,在numpy中工作。
>>> np.vstack([np.arange(x[0], x[-1]), np.repeat(yp, np.diff(x))]).T
array([[1001, 0],
[1002, 0],
[1003, 0],
...
[1020, 1],
...
[1050, 1]])