pandas DataFrame diagonal
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