相关疑难解决方法(0)

在NumPy阵列的每个单元处有效地评估函数

给定NumPy数组A,将相同函数f应用于每个单元格的最快/最有效的方法是什么?

  1. 假设我们将分配给A(I,J)F(A(I,J)) .

  2. 函数f没有二进制输出,因此掩码(ing)操作无济于事.

"明显的"双循环迭代(通过每个单元格)是最优解吗?

python performance numpy function vectorization

123
推荐指数
2
解决办法
11万
查看次数

从列表理解和一般情况下有效地创建numpy数组

在我目前的工作中,我使用Numpy和列表理解很多,为了最好的表现,我有以下问题:

如果我按如下方式创建Numpy数组,幕后实际发生了什么?:

a = numpy.array( [1,2,3,4] )
Run Code Online (Sandbox Code Playgroud)

我的猜测是python首先创建一个包含值的普通列表,然后使用列表大小来分配一个numpy数组,然后将值复制到这个新数组中.这是正确的,还是解释器聪明到足以意识到列表只是中介而是直接复制值?

同样,如果我希望使用numpy.fromiter()从列表理解中创建一个numpy数组:

a = numpy.fromiter( [ x for x in xrange(0,4) ], int )
Run Code Online (Sandbox Code Playgroud)

这会导致在被送入fromiter()之前创建的值的中间列表吗?

最好的问候尼尔斯

python performance numpy

36
推荐指数
2
解决办法
2万
查看次数

在返回向量的函数上使用Numpy Vectorize

numpy.vectorize 取函数f:a-> b并将其变为g:a [] - > b [].

这在标量ab标量时都可以正常工作,但是我想不出为什么它不能用b作为ndarray或列表,即f:a-> b []和g:a [] - > b [] []

例如:

import numpy as np
def f(x):
    return x * np.array([1,1,1,1,1], dtype=np.float32)
g = np.vectorize(f, otypes=[np.ndarray])
a = np.arange(4)
print(g(a))
Run Code Online (Sandbox Code Playgroud)

这会产生:

array([[ 0.  0.  0.  0.  0.],
       [ 1.  1.  1.  1.  1.],
       [ 2.  2.  2.  2.  2.],
       [ 3.  3.  3.  3.  3.]], dtype=object)
Run Code Online (Sandbox Code Playgroud)

好的,所以给出了正确的值,但错误的dtype.更糟糕的是:

g(a).shape
Run Code Online (Sandbox Code Playgroud)

收益率:

(4,)
Run Code Online (Sandbox Code Playgroud)

所以这个阵列几乎没用.我知道我可以将其转换为:

np.array(map(list, a), dtype=np.float32)
Run Code Online (Sandbox Code Playgroud)

给我我想要的东西:

array([[ 0., …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy vectorization

31
推荐指数
3
解决办法
4万
查看次数

访问numpy数组的相邻单元格

如何以有效的方式访问和修改2D numpy阵列的周围8个单元?

我有一个像这样的2D numpy数组:

arr = np.random.rand(720, 1440)
Run Code Online (Sandbox Code Playgroud)

对于每个网格单元,我想减少中心单元的10%,周围的8个单元(角单元更少),但仅当周围单元值超过0.25时.我怀疑这样做的唯一方法是使用for循环但是想看看是否有更好/更快的解决方案.

- 编辑:对于基于循环的soln:

arr = np.random.rand(720, 1440)

for (x, y), value in np.ndenumerate(arr):
    # Find 10% of current cell
    reduce_by = value * 0.1

    # Reduce the nearby 8 cells by 'reduce_by' but only if the cell value exceeds 0.25
    # [0] [1] [2]
    # [3] [*] [5]
    # [6] [7] [8]
    # * refers to current cell

    # cell [0]
    arr[x-1][y+1] = arr[x-1][y+1] * reduce_by if arr[x-1][y+1] > 0.25 else arr[x-1][y+1] …
Run Code Online (Sandbox Code Playgroud)

python numpy

17
推荐指数
1
解决办法
1763
查看次数

沿numpy数组应用函数

我有以下numpy ndarray.

[ -0.54761371  17.04850603   4.86054302]
Run Code Online (Sandbox Code Playgroud)

我想将此函数应用于数组的所有元素

def sigmoid(x):
  return 1 / (1 + math.exp(-x))

probabilities = np.apply_along_axis(sigmoid, -1, scores)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误.

TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么.

python numpy

8
推荐指数
2
解决办法
1万
查看次数

将函数应用于 NumPy 矩阵中的所有元素

假设我创建了一个 3x3 NumPy 矩阵。将函数应用于矩阵中的所有元素(如果可能的话,无需循环遍历每个元素)的最佳方法是什么?

import numpy as np    

def myFunction(x):
return (x * 2) + 3

myMatrix = np.matlib.zeros((4, 4))

# What is the best way to apply myFunction to each element in myMatrix?
Run Code Online (Sandbox Code Playgroud)

编辑:如果该函数是矩阵友好的,那么当前提出的解决方案效果很好,但是如果它是这样一个仅处理标量的函数呢?

def randomize():
    x = random.randrange(0, 10)
    if x < 5:
        x = -1
    return x
Run Code Online (Sandbox Code Playgroud)

唯一的方法是循环遍历矩阵并将函数应用于矩阵内的每个标量吗?我不是在寻找特定的解决方案(例如如何随机化矩阵),而是在寻找在矩阵上应用函数的通用解决方案希望这可以帮助!

python numpy matrix python-3.x

7
推荐指数
1
解决办法
2万
查看次数

numpy faster than numba and cython , how to improve numba code

I have a simple example here to help me understand using numba and cython. I am `new to both numba and cython. I've tried my best with to incorporate all the tricks to make numba fast and to some extent, the same for cython but my numpy code is almost 2x faster than numba (for float64), more than 2x faster if using float32. Not sure what I am missing here.

I was thinking perhaps the problem isn't coding anymore but …

python performance numpy cython numba

5
推荐指数
3
解决办法
385
查看次数

Python pandas: how to obtain the datatypes of objects in a mixed-datatype column?

Given a pandas.DataFrame with a column holding mixed datatypes, like e.g.

df = pd.DataFrame({'mixed': [pd.Timestamp('2020-10-04'), 999, 'a string']})
Run Code Online (Sandbox Code Playgroud)

I was wondering how to obtain the datatypes of the individual objects in the column (Series)? Suppose I want to modify all entries in the Series that are of a certain type, like multiply all integers by some factor.

I could iteratively derive a mask and use it in loc, like

m = np.array([isinstance(v, int) for v in df['mixed']])

df.loc[m, 'mixed'] …
Run Code Online (Sandbox Code Playgroud)

python types pandas

5
推荐指数
1
解决办法
272
查看次数

如何使用两个相同维度的矩阵执行逐元素自定义函数

未能找到任何这方面的信息。如果我有两个维度相同的 mxn 矩阵,有没有办法在 numty 中对它们应用逐元素函数?为了说明我的意思:

自定义函数为 F(x,y)

第一个矩阵:

array([[ a, b],
       [ c, d],
       [ e, f]])
Run Code Online (Sandbox Code Playgroud)

第二个矩阵:

array([[ g, h],
       [ i, j],
       [ k, l]])
Run Code Online (Sandbox Code Playgroud)

有没有办法在 numpy 中使用上述两个矩阵来获得下面所需的输出

array([[ F(a,g), F(b,h)],
       [ F(c,i), F(d,j)],
       [ F(e,k), F(f,l)]])
Run Code Online (Sandbox Code Playgroud)

我知道我可以只做嵌套for语句,但我想可能有一种更干净的方法

python numpy linear-algebra

4
推荐指数
1
解决办法
2074
查看次数

从列表中返回值!!= 2

我有一个列表,例如 my_list = [1, 3, 5, 7, 14, 16, 18, 22, 28, 30, 32, 41, 43]

我想要一个函数,它将返回列表中的所有值,其中该值与前一个值之间的差值不等于2,例如,函数将返回[1, 14, 22, 28, 41]上面的列表.请注意,第一个值my_list将始终显示为输出的第一个值.输入列表的长度不为零,最大为100.

到目前为止我有这个:

def get_output(array):
    start = [array[0]]
    for i in range(1, len(array)-1):
        if (array[i] - array[i-1]) != 2:
            start.append(array[i])

    return start
Run Code Online (Sandbox Code Playgroud)

是否有更快的矢量化解决方案,请记住我将这个函数应用于数千个输入数组?

python arrays numpy

3
推荐指数
1
解决办法
113
查看次数

跨越numpy矩阵的映射函数

有没有办法轻松地将函数映射到 numpy 数组中的每个值?我之前通过将其拆分为列表,使用列表理解并重新制作矩阵来完成它,但似乎必须有一种更简单的方法。

python numpy python-3.x

3
推荐指数
1
解决办法
9326
查看次数

md5 numpy 数组的快速方法

我正在使用 python 2.7 中包含数千个 uint64 数字的 numpy 一维数组。分别计算每个数字的 md5 的最快方法是什么?

在调用 md5 函数之前,每个数字都必须转换为字符串。我在很多地方都读到迭代 numpy 的数组并在纯 python 中做事非常慢。有什么办法可以规避吗?

python hash md5 numpy

3
推荐指数
1
解决办法
1836
查看次数

Lambda 函数 - 类型错误:不可散列的类型:'numpy.ndarray'

我有一个 numpy 二维数组,每列都有分类数据。

我尝试对每列的数据进行单独编码,同时可能在每种情况下处理看不见的数据。

我有这个代码:

from sklearn.preprocessing import LabelEncoder

for column in range(X_train.shape[1]):

    label_encoder = LabelEncoder()

    X_train[:, column] = label_encoder.fit_transform(X_train[:, column])

    mappings = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))

    map_function = lambda x: mappings.get(x, -1)

    X_test[:, column] = map_function(X_test[:, column])
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-***********> in <module>
     39         mappings = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
     40         map_function = lambda x: mappings.get(x, -1)
---> 41         X_test[:, column] = map_function(X_test[:, column])
     42 
     43 

<ipython-input-***********> in <lambda>(x)
     38         X_train[:, column] = label_encoder.fit_transform(X_train[:, column])
     39         mappings = …
Run Code Online (Sandbox Code Playgroud)

python lambda encoding numpy categorical-data

2
推荐指数
1
解决办法
968
查看次数