Re: [問題] numpy問題請教

看板Python作者 (沛行)時間4年前 (2019/12/02 17:39), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
已經很接近了,但因為不知道你取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://www.ptt.cc/bbs/Python/M.1575279550.A.8EE.html
文章代碼(AID): #1TvDk-Zk (Python)
文章代碼(AID): #1TvDk-Zk (Python)