相关疑难解决方法(0)

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

我有一个矩形(不能假设是正方形)的Pandas DataFrame数字.假设我选择了一个对角线方向("左上角到右下角"或"右上角到左下角").我想计算一个系列,其条目是沿着所选并行对角线的原始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
Run Code Online (Sandbox Code Playgroud)

我可以如下计算"左上角到右下角"的对角线总和:

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
Run Code Online (Sandbox Code Playgroud)

我可以通过翻转前面的shift(-i)to 来计算"右上角"对角线总和shift(i):

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

python numpy pandas

10
推荐指数
1
解决办法
1097
查看次数

剪一个numpy阵列

我想'剪切'一个numpy阵列.我不确定我是否正确使用"剪切"一词; 通过剪切,我的意思是:

将第一列
移动0个位置将第二列
移动1个位置将第三个列移动2个位置
等...

所以这个数组:

array([[11, 12, 13],
       [17, 18, 19],
       [35, 36, 37]])
Run Code Online (Sandbox Code Playgroud)

会变成这个数组:

array([[11, 36, 19],
       [17, 12, 37],
       [35, 18, 13]])
Run Code Online (Sandbox Code Playgroud)

或类似这样的数组:

array([[11,  0,  0],
       [17, 12,  0],
       [35, 18, 13]])
Run Code Online (Sandbox Code Playgroud)

取决于我们如何处理边缘.我不太关注边缘行为.

这是我尝试执行此操作的函数:

import numpy

def shear(a, strength=1, shift_axis=0, increase_axis=1, edges='clip'):
    strength = int(strength)
    shift_axis = int(shift_axis)
    increase_axis = int(increase_axis)
    if shift_axis == increase_axis:
        raise UserWarning("Shear can't shift in the direction it increases")
    temp = numpy.zeros(a.shape, dtype=int)
    indices = []
    for d, num in enumerate(a.shape): …
Run Code Online (Sandbox Code Playgroud)

python optimization numpy premature-optimization

8
推荐指数
3
解决办法
2728
查看次数