python - 在 Numpy/Pandas 中生成所有平行对角线总和的直接方法?

标签 python numpy pandas

我有一个矩形(不能假定为正方形)的 Pandas 数字数据框。假设我选择对角线方向(“左上角到右下角”或“右上角到左下角”)。我想计算一个系列,其条目是原始 DataFrame 沿所选平行对角线集的值的总和。要完全指定目标,您需要确定对角线是“锚定”在左侧还是“锚定”在右侧。对于下面的内容,我假设它们“锚定”在左侧。

我可以毫不费力地做到这一点:

import numpy as np
import pandas as pd

rectdf = pd.DataFrame(np.arange(15).reshape(5,3))

# result:
    0   1   2
0   0   1   2
1   3   4   5
2   6   7   8
3   9  10  11
4  12  13  14

我可以按如下方式计算“左上角到右下角”的对角线和:

ullrsums = pd.concat([rectdf.iloc[:, i].shift(-i) for i in range(rectdf.shape[1])], axis=1)\
    .sum(axis=1, fillna=0)

# result:
0    12
1    21
2    30
3    22
4    12

我可以通过将 shift(-i) 翻转为 shift(i) 来计算“右上角到左下角”的对角线和:

urllsums = pd.concat([rectdf.iloc[:, i].shift(i) for i in range(rectdf.shape[1])], axis=1)\
    .sum(axis=1, fillna=0)

# result:
0     0
1     4
2    12
3    21
4    30

这些结果都是正确的(即这段代码做了我想要的)。在 Pandas 或 Numpy 中是否有更直接的方法来计算这些总和?

最佳答案

您可能正在寻找 numpy.trace(),已记录 here , 直接获取迹线,或 numpy.diagonal() 获取对角向量,documented here

首先,使用 rectdf.as_matrix()

将您的数据帧转换为 numpy 矩阵

然后:

np.trace(matrix, offset)

偏移量可以是正数也可以是负数,它会执行您需要的移动。

例如,如果我们这样做:

a = np.arange(15).reshape(5, 3)
for x in range(-4, 3): print np.trace(a, x)

我们得到输出:

12
22
30
21
12
6
2

要对一般矩阵执行此操作,我们需要从 -(rows - 1)columns 的范围,即如果我们有一个变量 rows 和一个变量 columns:

a = np.arange(rows * columns).reshape(rows, columns)
for x in range(-(rows - 1), columns): print np.trace(a, x)

关于python - 在 Numpy/Pandas 中生成所有平行对角线总和的直接方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066820/

相关文章:

python - 属性错误: 'NoneType' object has no attribute 'group'

python - mypy 是否有子类可接受的返回类型?

python - 如何找到具有相同 ID 的所有变量?

Python numpy 类型小数位数

python - 如何从 Excel 单元格中读取列表

Python 请求 422 post 错误

python - 使用 .loc 查询非空值和仅字符串值

python-2.7 - python map 和 numpy vectorize 的不同结果

python - 将以秒为单位的时间戳转换为 hh :mm:ss time

python - 在按 DataFrame 列着色图时,如何设置每个值的颜色?