Following pandas DataFrame diagonal, I can get diagonal elements using np.diag
. How can I get the non-diagonal elements in a dataframe (assuming that dataframe is size n x n)
So in order to get the sum of the non-diagonal parts of the matrix: Traverse the matrix rowwise. If the element is a part of diagonal, then skip this element. If the element is part of the left, right, bottom, or top part (i.e. non-diagonal parts), add the element in the resultant sum.
The elements which do not lie on the leading diagonal of a square matrix is called non-diagonal elements of the matrix. The number of rows is equal to the number of columns in a square matrix. So, a principal diagonal is formed by the first element of first row and last element of last row.
With the help of Numpy matrix. diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix.
Use a mask generated with np.eye
like:
xf = pd.DataFrame(np.random.rand(5,5))
xf.mask(np.eye(5, dtype = bool))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With