2次元ndarrayで1つの列を他の列と比較するための正しいnumpy構文は何ですか?
アレイブロードキャストに関するいくつかの ドキュメントを読んだ後でも、これを行う正しい方法が何であるかはまだよくわかりません。
例: 各ゲーム (列) で各プレーヤー (行) が得点したゴールの 2 次元配列があるとします。
# goals = number of goals scored by ith player in jth game (NaN if player did not play)
# column = game
goals = np.array([ [np.nan, 0, 1], # row = player
[ 1, 2, 0],
[ 0, 0, np.nan],
[np.nan, 1, 1],
[ 0, 0, 1] ])
最終ゲームで、プレーヤーが以前のゲームよりも多くのゴールを決めて個人記録を達成したかどうかを知りたいですnan
。True
配列内の最初と最後のプレーヤーのみ を期待しています。
書くだけgoals[:,2] > goals[:,:2]
でValueError: operands could not be broadcast together with shapes (5,) (5,2)
私が試したこと:(5,)
手動でをに引き伸ばすことができることを知ってい(5,2)
ますnp.newaxis
。したがって、これは機能します:
with np.errstate(invalid='ignore'):
personalBest= ( np.isnan(goals[:,:2]) |
(goals[:,2][:,np.newaxis] > goals[:,:2] )
).all(axis=1)
print(personalBest) # returns desired solution
これを書くためのハックが少なく、より慣用的にnumpyな方法はありますか?