I have the following data frame which can be copy/pasted and made to a data frame with: df = pd.read_clipboard()
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 0 1 5 12 13 7 1 5 5 1 7 13 12 5 1 0 1 1 0 4 13 12 6 0 4 4 0 6 12 13 4 0 1 2 5 4 0 9 8 2 4 0 0 4 2 8 9 0 4 5 3 12 13 9 0 1 11 13 9 9 13 11 1 0 9 13 12 4 13 12 8 1 0 10 12 8 8 12 10 0 1 8 12 13 5 7 6 2 11 10 0 6 2 2 6 0 10 11 2 6 7 6 1 0 4 13 12 6 0 4 4 0 6 12 13 4 0 1 7 5 4 0 9 8 2 4 0 0 4 2 8 9 0 4 5 8 5 4 0 9 8 2 4 0 0 4 2 8 9 0 4 5 9 1 0 4 13 12 6 0 4 4 0 6 12 13 4 0 1 10 7 6 2 11 10 0 6 2 2 6 0 10 11 2 6 7 11 13 12 8 1 0 10 12 8 8 12 10 0 1 8 12 13 12 12 13 9 0 1 11 13 9 9 13 11 1 0 9 13 12 13 5 4 0 9 8 2 4 0 0 4 2 8 9 0 4 5 14 1 0 4 13 12 6 0 4 4 0 6 12 13 4 0 1 15 0 1 5 12 13 7 1 5 5 1 7 13 12 5 1 0
I would like to take a cross section from it, I want something like say:
[1, 4, 9, 1, 10, 6, 4, 0, 4, 6, 10, 1, 9, 4, 1])
which is index df.loc[1, 0], df.loc[2, 1], df.loc[3, 2], df.loc[4, 3], etc.
Is there a numpy or pandas pattern to do get this type of cross slice easier than with many different indexes like which I’m doing? Thanks.
Advertisement
Answer
We can use np.diagonal
with offset=1
to select the diagonal elements above the main diagonal
np.diagonal(df, offset=1)
array([ 1, 4, 9, 1, 10, 6, 4, 0, 4, 6, 10, 1, 9, 4, 1])