[英]Pulling data from a numpy array
我有一个使用numpy.loadtxt制作的numpy ndarray。 我想根据第三列中的条件从中拉出整行。 类似于:如果array [2] [i]符合我的条件,那么也得到数组[0] [i]和数组[1] [i]。 我是python的新手,以及所有的numpy功能,所以我正在寻找最好的方法来做到这一点。 理想情况下,我想一次拉2行,但我不会总是有偶数行,所以我想这是一个问题
import numpy as np
'''
Created on Jan 27, 2013
@author:
'''
class Volume:
f ='/Users/Documents/workspace/findMinMax/crapc.txt'
m = np.loadtxt(f, unpack=True, usecols=(1,2,3), ndmin = 2)
maxZ = max(m[2])
minZ = min(m[2])
print("Maximum Z value: " + str(maxZ))
print("Minimum Z value: " + str(minZ))
zIncrement = .5
steps = maxZ/zIncrement
currentStep = .5
b = []
for i in m[2]:#here is my problem
while currentStep < steps:
if m[2][i] < currentStep and m[2][i] > currentStep - zIncrement:
b.append(m[2][i])
if len(b) < 2:
currentStep + zIncrement
print(b)
这是我在java中做的一些代码,它是我想要的一般概念:
while( e < a.length - 1){
for(int i = 0; i < a.length - 1; i++){
if(a[i][2] < stepSize && a[i][2] > stepSize - 2){
x.add(a[i][0]);
y.add(a[i][1]);
z.add(a[i][2]);
}
if(x.size() < 1){
stepSize += 1;
}
}
}
首先,您可能不希望将代码放在该类定义中......
import numpy as np
def main():
m = np.random.random((3, 4))
mask = (m[2] > 0.5) & (m[2] < 0.8) # put your conditions here
# instead of 0.5 and 0.8 you can use
# an array if you like
m[:, mask]
if __name__ == '__main__':
main()
mask
是一个布尔数组, m[:, mask]
是你想要的数组
m [2]是m的第三行。 如果输入m[2] + 2
则会得到一个带有旧值+ 2的新数组m[2] > 0.5
会创建一个带有布尔值的数组。 最好用ipython(www.ipython.org)试试这个东西。
在表达式m[:, mask]
, :
表示“取所有行”,mask表示应包含哪些列。
更新
接下来尝试:-)
for i in range(0, len(m), 2):
two_rows = m[i:i+2]
如果你可以把你的条件写成一个简单的函数
def condition(value):
# return True or False depending on value
然后你可以像这样选择你的子阵列:
cond = condition(a[2])
subarray0 = a[0,cond]
subarray1 = a[1,cond]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.