Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy. trace() and numpy. diagonal() method.
diagonal() 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.
I have a rectangular (can't be assumed to be square) Pandas DataFrame of numbers. Say I pick a diagonal direction (either "upperleft to lowerright" or "upperright to lowerleft"). I'd like to compute a series whose entries are the sums of the values from the original DataFrame along the chosen set of parallel diagonals. To fully specify the goal, you need to decide whether diagonals are "anchored" on the left or "anchored" on the right. For the below, I assume they're "anchored" on the left.
I can do this without too much trouble:
import numpy as np
import pandas as pd
rectdf = pd.DataFrame(np.arange(15).reshape(5,3))
# result:
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
4 12 13 14
I can compute the "upperleft to lowerright" diagonal sums as follows:
ullrsums = pd.concat([rectdf.iloc[:, i].shift(-i) for i in range(rectdf.shape[1])], axis=1)\
.sum(axis=1, fillna=0)
# result:
0 12
1 21
2 30
3 22
4 12
And I can compute the "upperright to lowerleft" diagonal sums by flipping the shift(-i)
to shift(i)
in the previous:
urllsums = pd.concat([rectdf.iloc[:, i].shift(i) for i in range(rectdf.shape[1])], axis=1)\
.sum(axis=1, fillna=0)
# result:
0 0
1 4
2 12
3 21
4 30
These results are all correct (i.e. this code does what I want). Is there a more direct way to compute these sums in Pandas or Numpy?
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