piR*_*red 21 python numpy pandas
什么是获得正方形对角线的有效方法DataFrame.我希望结果是一个Series有MultiIndex两个级别的,第一个是DataFrame第二个级别的索引是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
)
Run Code Online (Sandbox Code Playgroud)
我想看到这个:
print df.stack().loc[[('A', 'a'), ('B', 'b'), ('C', 'c')]]
A a 2
B b 2
C c 3
Run Code Online (Sandbox Code Playgroud)
joh*_*ase 30
如果你不介意使用numpy你可以使用 numpy.diag
pd.Series(np.diag(df), index=[df.index, df.columns])
A a 2
B b 2
C c 3
dtype: int64
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
In [16]:
midx = pd.MultiIndex.from_tuples(list(zip(df.index,df.columns)))
pd.DataFrame(data=np.diag(df), index=midx)
Out[16]:
0
A a 2
B b 2
C c 3
Run Code Online (Sandbox Code Playgroud)
np.diag将给出对角线值为np数组,然后可以通过压缩索引和列来构造多索引,并将其作为DataFramector中的所需索引传递.
实际上,复杂的多索引生成并不需要如此复杂:
In [18]:
pd.DataFrame(np.diag(df), index=[df.index, df.columns])
Out[18]:
0
A a 2
B b 2
C c 3
Run Code Online (Sandbox Code Playgroud)
但johnchase的答案更简洁
您还可以在列表理解中使用iat来获取对角线。
>>> pd.Series([df.iat[n, n] for n in range(len(df))], index=[df.index, df.columns])
A a 2
B b 2
C c 3
dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14856 次 |
| 最近记录: |