Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you slice a cross section in pandas or numpy?

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])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading