以下 numpy 代码的 KDB 等价物是什么

What's the KDB equivalent of the following numpy code

我正在尝试获取更多 Q,所以我很好奇 Q 中实现以下目标的最佳方法。

In [18]: a = np.arange(12).reshape(3,4)

In [19]: b=np.random.randint(10, size=(3, 4))

In [20]: a Out[20]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])

In [21]: b Out[21]: array([[3, 6, 9, 5], [4, 2, 1, 3], [6, 9, 3, 5]])

In [22]: a[a>5] = b[a>5]

In [23]: a Out[23]: array([[0, 1, 2, 3], [4, 5, 1, 3], [6, 9, 3, 5]])

还有什么好办法,

a[np.where(cond)] = b[np.where(cond)]

谢谢!

a: 3 4#til 12 // 按照上述逻辑初始化一个矩阵

b: 3 4# 12?10 // 按照上述逻辑初始化 b 矩阵

@'[一个;吨; :; b @' t: where each a > 5] // 基于以上逻辑

下面提到了您的命令的等效 KDB 操作。

注意:请注意,这些 KDB 和 numpy 函数并不完全 相等的。它们仅在某些输入条件下表现相似。详细阅读 KDB 函数的行为,因为 他们超载了。 我在底部提供了此处使用的 kdb 运算符的链接。

1. a = np.arange(12).reshape(3,4)

KDB 中具有单输入的 numpy 'arange' 等价于 'til' 运算符。 KDB 中的重塑运算符是“#”。

等效的 KDB 命令是:

 q) a:2 4 #til 12

2。 b=np.random.randint(10, 大小=(3, 4))

'?' KDB 中的运算符给出随机值。它不支持尺寸,但可以使用形状运算符轻松实现。

q) 2? 4  / output 1 3 (2 random values)
q) 3 4# 12?10

或者我们可以为此创建一个通用函数:

q) {(y;z )#?[y*z;x]} [8 ;3 ;4]

3。 a[np.where(cond)] = b[np.where(cond)]

在 KDB 中有不同的方法可以做到这一点。使用哪种解决方案取决于您的列表大小。有些会表现更好 在小名单上,有些会在大名单上表现更好。因此,请根据您的项目进行测试。

下面提到的所有三种解决方案都会为您提供所需的输出。

q) a: 3 4#til 12;
q) b: (3 6 9 5;4 2 1 3;6 9 3 5)

q) a:(a*not i)+b*i:a>5  /solution 1

使用 @ 和 each-both

q) a:{@[x;y;:;z]}'[a;i;b@'i: where each a > 5] / solution 2
q) a:@'[a;i;:;b@'i: where each a > 5]  /short form

或使用点 (.) 运算符就地更改原始数组:

 q) l:(til count a),'enlist each where@'a>5 
 q) {.[`a;x;:;y]}'[l;b ./:l]  /solution 3
 q) .'[`a;l;:;b ./:l]  short form

在此处阅读更多详细信息:

https://code.kx.com/q/ref/card/

https://code.kx.com/q/ref/arith-integer/#til

https://code.kx.com/q/ref/unclassified/#apply

https://code.kx.com/q/ref/select/#index-at

https://code.kx.com/q/ref/random/#roll