pandas DataFrame diagonal pandas DataFrame diagonal numpy numpy

pandas DataFrame diagonal


If you don't mind using numpy you could use numpy.diag

pd.Series(np.diag(df), index=[df.index, df.columns])A  a    2B  b    2C  c    3dtype: int64


You could do something like this:

In [16]:midx = pd.MultiIndex.from_tuples(list(zip(df.index,df.columns)))pd.DataFrame(data=np.diag(df), index=midx)Out[16]:     0A a  2B b  2C c  3

np.diag will give you the diagonal values as a np array, you can then construct the multiindex by zipping the index and columns and pass this as the desired index in the DataFrame ctor.

Actually the complex multiindex generation doesn't need to be so complicated:

In [18]:pd.DataFrame(np.diag(df), index=[df.index, df.columns])Out[18]:     0A a  2B b  2C c  3

But johnchase's answer is neater


You can also use iat in a list comprehension to get the diagonal.

>>> pd.Series([df.iat[n, n] for n in range(len(df))], index=[df.index, df.columns]) A  a    2B  b    2C  c    3dtype: int64