how to select values on the diagonal pandas dataframe in python

We can select values on the diagonal of a pandas DataFrame using the numpy method diagonal(). Here's an example:

main.py
import pandas as pd
import numpy as np

# create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# get diagonal values
diag = np.diagonal(df)

# print diagonal values
print(diag)
219 chars
12 lines

This will output:

main.py
array([1, 5, 9])
17 chars
2 lines

Note that this approach assumes that the DataFrame has a square shape (i.e. the number of rows and columns are equal). If the DataFrame is not square, you'll need to first extract the square subset of the DataFrame that contains the diagonal, and then apply np.diagonal().

related categories

gistlibby LogSnag