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 can I extract different diagonals of a DataFrame?

I happen to have a dataset that looks like this:

A-B     A-B     A-B     A-B     A-B     B-A     B-A     B-A     B-A     B-A  
 2       3       2       4       5      3.1      3       2      2.5     2.6
NaN     3.2     3.3     3.5     5.2     NaN      4      2.7     3.2      5
NaN     NaN     4.1      4       6      NaN     NaN      4      4.1      6
NaN     NaN     NaN     4.2     5.1     NaN     NaN     NaN     3.5     5.2
NaN     NaN     NaN     NaN      6      NaN     NaN     NaN     NaN     5.7

It’s very bad, I know. But what I would like to obtain is:

A-B     B-A
 2      3.1
3.2      4
4.1      4
4.2     3.5
 6      5.7

Which are the values on the "diagonals"

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

Is there a way I can get something like this?

>Solution :

You could use groupby and a dictionary comprehension with numpy.diag:

df2 = pd.DataFrame({x: np.diag(g) for x, g in df.groupby(level=0, axis=1)})

output:

   A-B  B-A
0  2.0  3.1
1  3.2  4.0
2  4.1  4.0
3  4.2  3.5
4  6.0  5.7
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