我试图扫描数组中的值,并根据结果采取行动。然而,当我仔细查看代码正在做什么时,我注意到我的逻辑状态是病态的。
我将用下面的例子来说明我的意思:
#importing numpy
import numpy as np
#creating a test array
a = np.zeros((3,3))
#searching items bigger than 1 in 'a'
index = np.where(a > 1)
我原以为我的索引会返回一个空列表。实际上,它返回一个tuple对象,如:
index
Out[5]: (array([], dtype=int64)
我经常需要堆叠2d的numpy数组(tiff图像)。为此,我首先将它们添加到列表中并使用np.dstack。这似乎是获得3D数组堆叠图像的最快方法。但是,有没有一种更快/更有效的记忆方式?
from time import time
import numpy as np
# Create 100 images of the same dimention 256x512 (8-bit).
# In reality, each image comes from a different file
img = np.random.randint(0,255,(256, 512, 100))
t0
我有:
>>> a
array([[1, 2],
[3, 4]])
>>> type(l), l # list of scalers
(<type 'list'>, [0, 1])
>>> type(i), i # a numpy array
(<type 'numpy.ndarray'>, array([0, 1]))
>>> type(j), j # list of numpy arrays
(<type 'list'&g
为了解决一个只可能逐个元素的问题,我需要将NumPy的元组索引和一个显式切片结合起来。
def f(shape, n):
"""
:param shape: any shape of an array
:type shape: tuple
:type n: int
"""
x = numpy.zeros( (n,) + shape )
for i in numpy.ndindex(shape): # i = (k, l, ...)
x[:,
现在,我正在尝试理解索引numpy结构化数组的可能方法,而且我有点被它困住了。仅举几个简单的例子:
import numpy as np
arr = np.array(zip(range(5), range(5, 10)), dtype=[('a', int), ('b', int)])
arr[0] # first row (record)
arr[(0,)] # the same, as expected
arr['a'] # field 'a' of each record
arr[('a',)] # &
为什么pandas.DataFrame的操作这么慢?!看下面的例子。
计量:
创建一个由随机浮点数填充的numpy.ndarray 创建一个用相同的填充的pandas.DataFrame
I度量下列操作的时间
numpy.ndarray的
- Take the sum along the 0-axis
- Take the sum along the 1-axis
pandas.DataFrame的
- Take the sum along the 0-axis
- Take the sum along the 1-axis
pandas.DataFrame.values ->
我见过,我以为它会回答我的问题,但它没有。
因此,我准备了一个基于文章中的一个例子的例子,它显示了我想做什么,以及我被困在了什么地方:
import numpy as np
# based on https://stackoverflow.com/a/48716125/6197439
# arr is a numpy array of tuple "pairs" of floats
oarr = [(0.109, 0.5), (0.109, 0.55), (0.109, 0.6), (0.2, 0.4), (0.3, 0.5)]
arr = np.array(oarr)
p
我有一个python脚本,作为进化优化算法的一部分,我对偏导数进行了数千次计算。我做了一个逐行的概要,这个偏导数计算占用了大部分的运行时间。我使用scipy.optimize.approx_fprime来计算偏导数,并尝试用Cython语言重写它,但没有成功。
逐行配置文件如下所示。我的scipy.optimize.approx_fprime的cythonized版本被简单地称为approx_fprime。
Line # Hits Time Per Hit % Time Line Contents
===============================
我想使用numpy.where中的索引值来打印该索引的字符串内容。我试图通过迭代从0到数组长度的数组来做到这一点。但长度始终是1..?
import numpy as np
v,w,x, y, z = np.loadtxt('test.txt', dtype=str, delimiter='|',
skiprows=2,usecols=(0,1,2,3,4), unpack=True)
a,b,c, d, e = np.loadtxt('test2.txt', dtype=str, del
我试图将过滤后的值从Numpy数组传递到一个函数中。我只需要通过Numpy数组传递高于某个值的值,以及它们的索引位置。
我试图通过使用Numpys自己的过滤系统来避免迭代python中的整个数组,我正在处理的数组中有20k的值,可能只有很少的值是相关的。
import numpy as np
somearray = np.array([1,2,3,4,5,6])
arrayindex = np.nonzero(somearray > 4)
for i in arrayindex:
somefunction(arrayindex[0], somearray[arrayindex
我试图创建一个简单的数值积分函数来说明高维蒙特卡罗积分的好处。我想要这样的东西:
def quad_int(f, mins, maxs, numPoints=100):
'''
Use the naive (Riemann sum) method to numerically integrate f on a box
defined by the mins and maxs.
INPUTS:
f - A function handle. Should accept a 1-D NumPy array