Home:ALL Converter>get indicies of non-zero elements of 2D array

get indicies of non-zero elements of 2D array

Ask Time:2017-05-21T11:24:00         Author:user308827

Json Formatter

From Getting indices of both zero and nonzero elements in array, I can get indicies of non-zero elements in a 1 D array in numpy like this:

indices_nonzero = numpy.arange(len(array))[~bindices_zero]

Is there a way to extend it to a 2D array?

Author:user308827,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44092848/get-indicies-of-non-zero-elements-of-2d-array
Mo... :

You can use numpy.nonzero\n\nThe following code is self-explanatory\n\nimport numpy as np\n\nA = np.array([[1, 0, 1],\n [0, 5, 1],\n [3, 0, 0]])\nnonzero = np.nonzero(A)\n# Returns a tuple of (nonzero_row_index, nonzero_col_index)\n# That is (array([0, 0, 1, 1, 2]), array([0, 2, 1, 2, 0]))\n\nnonzero_row = nonzero[0]\nnonzero_col = nonzero[1]\n\nfor row, col in zip(nonzero_row, nonzero_col):\n print(\"A[{}, {}] = {}\".format(row, col, A[row, col]))\n\"\"\"\nA[0, 0] = 1\nA[0, 2] = 1\nA[1, 1] = 5\nA[1, 2] = 1\nA[2, 0] = 3\n\"\"\"\n\n\nYou can even do this\n\nA[nonzero] = -100\nprint(A)\n\"\"\"\n[[-100 0 -100]\n [ 0 -100 -100]\n [-100 0 0]]\n \"\"\"\n\n\nOther variations\n\nnp.where(array)\n\nIt is equivalent to np.nonzero(array) \nBut, np.nonzero is preferred because its name is clear\n\nnp.argwhere(array)\n\nIt's equivalent to np.transpose(np.nonzero(array))\n\nprint(np.argwhere(A))\n\"\"\"\n[[0 0]\n [0 2]\n [1 1]\n [1 2]\n [2 0]]\n \"\"\"\n",
2017-05-21T03:27:55
yy