作者benson415 (沛行)
看板Python
标题Re: [问题] numpy问题请教
时间Mon Dec 2 17:39:07 2019
已经很接近了,但因为不知道你取incremental subset是否也要包括第一个
所以我提供了比较罗嗦但弹性一点的做法
以下两个numpy方法提供参考
https://gist.github.com/benbenbang/8e947fbd3c40c130ec99347f9c355873
------
import numpy as np
# Set an anchor
# This won't include the first element
# So you can prevent getting [5, 6] instead of [6] in a case like [5, 6, 8, 4]
# But if you like to include 5, then simply assign 0 to the idx
def method_np_diff(l, idx=1):
ary = np.array(l).reshape(-1)
# Stick with numpy diff
diff = np.diff(ary, append=ary[0])
# This will give you array([3, 4])
increasing_subset = ary[idx:][
(np.diff(ary, append=ary[0]) > 0)[idx:]
& (np.diff(ary, prepend=ary[-1]) > 0)[idx:]
]
return diff, increasing_subset
def method_np_roll(l, idx=1):
ary = np.array(l).reshape(-1)
# You can also try numpy roll
diff = np.roll(ary, -1) - ary
# This will give you array([3, 4]) as well
increasing_subset = ary[idx:][
(np.roll(ary, -1) - ary > 0)[idx:] & (ary - np.roll(ary, 1) > 0)[idx:]
]
return diff, increasing_subset
l = [5, 2, 3, 4, 6, 1]
print(
"Diff: %(diff)s | Incremental Subset: %(subset)s"
% {"diff": method_np_diff(l)[0], "subset": method_np_diff(l)[1]}
)
# 38.6 μs ± 2.67 μs per loop (mean ± std. dev. of 7 runs, 10000 loops
each)
%timeit method_np_diff(l)
# 38.1 μs ± 661 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit method_np_roll(l)
l = np.random.randn(10000000, 1)
# 115 ms ± 518 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit method_np_diff(l)
# 144 ms ± 293 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit method_np_roll(l)
基本上效能不会差太多,但一定比list comprehension或map + lambda取值好多了
欢迎回馈任何意见
※ 引述《xAyax (willy10155170)》之铭言:
: 有几个问题想要请教一下
: 如果想要比较一个一维阵列的每元素值
: 是否大於前一个且小於後一个
: 不用for用内建函式该怎麽做?
: Ex. A=[5, 2, 3,4,6,1]
: 我想取3,4因为2<3<4, 3<4<6
: 应该用np.where吗?
: 可是这样condition该怎麽填 囧
: 还有另一个问题是
: 如果有个二维阵列存各个点
: 我想计算所有各点间的距离
: 公式没问题
: 不过我要如何做到所有排列
: 一样不用for用内建函式的话
: Ex.[[点a],[点b],[点c]]
: 我想要计算ab, bc, ac间的距离
: 可是用np.diff只能算到ab,bc而已
: 我要如何做到连ac都算
: 希望有高人能指导一下
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 213.41.102.186 (法国)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1575279550.A.8EE.html