use*_*827 5 python numpy pandas
在pandas DataFrame对角线之后,我可以使用对角线元素np.diag.如何获取数据帧中的非对角元素(假设数据帧大小为nxn)
使用生成的掩码,np.eye如:
xf = pd.DataFrame(np.random.rand(5,5))
xf.mask(np.eye(5, dtype = bool))
Run Code Online (Sandbox Code Playgroud)
我将使用@Matt的相同数据帧 xf
xf = pd.DataFrame(np.random.rand(5, 5))
Run Code Online (Sandbox Code Playgroud)
但是,我会指出,如果对角线恰好等于零,则使用np.diag(np.diag(xf)) != 0将会中断.
保证屏蔽对角线的方法是评估行索引是否不等于列索引.
选项1
numpy.indices
方便地,numpy通过np.indices功能提供这些.
观察它们的样子
rows, cols = np.indices((5, 5))
print(rows)
[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]
print(cols)
[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]]
Run Code Online (Sandbox Code Playgroud)
它们相等的地方......对角线.
print((cols == rows).astype(int))
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]]
Run Code Online (Sandbox Code Playgroud)
因此,通过这些,我们可以掩盖它们相等的位置
xf.mask(np.equal(*np.indices(xf.shape)))
0 1 2 3 4
0 NaN 0.605436 0.573386 0.978588 0.160986
1 0.295911 NaN 0.509203 0.692233 0.717464
2 0.275767 0.966976 NaN 0.883339 0.143704
3 0.628941 0.668836 0.468928 NaN 0.309901
4 0.286933 0.523243 0.693754 0.253426 NaN
Run Code Online (Sandbox Code Playgroud)
我们可以使用更快一点
pd.DataFrame(
np.where(np.equal(*np.indices(xf.shape)), np.nan, xf.values),
xf.index, xf.columns
)
Run Code Online (Sandbox Code Playgroud)
选项2
numpy.arange与切片分配
v = xf.values.copy()
i = j = np.arange(np.min(v.shape))
v[i, j] = np.nan
pd.DataFrame(v, xf.index, xf.columns)
0 1 2 3 4
0 NaN 0.605436 0.573386 0.978588 0.160986
1 0.295911 NaN 0.509203 0.692233 0.717464
2 0.275767 0.966976 NaN 0.883339 0.143704
3 0.628941 0.668836 0.468928 NaN 0.309901
4 0.286933 0.523243 0.693754 0.253426 NaN
Run Code Online (Sandbox Code Playgroud)
%%timeit
v = xf.values.copy()
i = j = np.arange(np.min(v.shape))
v[i, j] = np.nan
pd.DataFrame(v, xf.index, xf.columns)
%timeit pd.DataFrame(np.where(np.eye(np.min(xf.shape)), np.nan, xf.values), xf.index, xf.columns)
%timeit pd.DataFrame(np.where(np.equal(*np.indices(xf.shape)), np.nan, xf.values), xf.index, xf.columns)
%timeit xf.mask(np.equal(*np.indices(xf.shape)))
%timeit xf.mask(np.diag(np.diag(xf.values)) != 0)
%timeit xf.mask(np.eye(np.min(xf.shape), dtype=bool)
10000 loops, best of 3: 74.5 µs per loop
10000 loops, best of 3: 85.7 µs per loop
10000 loops, best of 3: 77 µs per loop
1000 loops, best of 3: 519 µs per loop
1000 loops, best of 3: 517 µs per loop
1000 loops, best of 3: 528 µs per loop
Run Code Online (Sandbox Code Playgroud)