获得平方DataFrame的对角线的有效方法是什么.我希望结果是带有两个级别的Series和MultiIndex,第一个是DataFrame的索引,第二个级别是DataFrame的列.
What is an efficient way to get the diagonal of a square DataFrame. I would expect the result to be a Series with a MultiIndex with two levels, the first being the index of the DataFrame the second level being the columns of the DataFrame.
import pandas as pd import numpy as np np.random.seed([3, 1415]) df = pd.DataFrame(np.random.rand(3, 3) * 5, columns = list('abc'), index = list('ABC'), dtype=np.int64 )我想看看这个:
print df.stack().loc[[('A', 'a'), ('B', 'b'), ('C', 'c')]] A a 2 B b 2 C c 3推荐答案
如果您不介意使用numpy,则可以使用numpy.diag
If you don't mind using numpy you could use numpy.diag
pd.Series(np.diag(df), index=[df.index, df.columns]) A a 2 B b 2 C c 3 dtype: int64