= np.array([1, 0, 1, 5, 5, 1]) array_2 = np.array([[1, 0, 1], [5, 5, 1]]) print np.where (array_1 > 2) print np.where(array_2 > 2) 打印结果: (array([3, 4]),) (array([1, 1]), array([0, 1])) 三目运算 例:将奇数转换为偶数,偶数转换为奇数: import numpy as np y = np.array([1, 2, 3, 4, 5, 6]) print np.where(y%2 == 0, y+1
社区自动同步,原文地址 http://blogtest.stackoverflow.club/use-np-where/ import: use & instead of and Simply, use np.where (condition1 & condition2) will get the right answer, but `np.where( list(condition1) and list(condition2
np.where1、返回满足条件的元素的索引import numpy as nparr=np.array([0, 1, 2, 3, 4, 5, 6])#找到数组中所有大于3的元素的索引indices=np.where npx=np.array([1, 2, 3, 4, 5])y=np.array([10, 20, 30, 40, 50])#根据条件选择元素,如果条件为真则选择x的元素,#否则选择y的元素result=np.where (x<3, x, y)print(result)#输出结果:[1 2 30 40 50]score_array=np.array([56, 61, 95])score_result=np.where( C':[1, 9, 5, 2, 5], 'D':[2, 1, 4, 8, 9] })#新建E列,如果A列中大于4且D列小于8,#则E列为True,否则为Falsedf['E']=np.where
还记得那个周五的下午,我盯着屏幕上这段代码发呆: df["category"] = np.where(df["score"] > 90, "A", np.where(df ["score"] > 80, "B", np.where(df["score"] > 70, "C", np.where(df["score "] > 60, "D", "F")))) 这仅仅是一个5级分类,但实际项目中,我遇到过12层嵌套的np.where()! np.where(large_df["score"] > 80, "B", np.where(large_df["score"] > 70, "C" 技术洞察:这就像去超市购物——np.where()是每次买新东西都推个空购物车重新装,而掩码赋值是直接在现有购物车里替换部分商品。
函数的基本调用语法有两种,一种是: import numpy as np np.where(arry) 此时,np.where函数输出arry中“真”值的坐标(‘真’也可以理解为非0)。 或者说np.where函数从arry中返回满足特定条件的元素。比如,它会返回满足特定条件数值的索引位置。 另一种是: import numpy as np np.where(cond, x, y) 此时,np.where函数满足cond条件输出x,不满足输出y。 此时,np.where函数满足y>5输出'm_5',不满足输出'lq_5'。 8] 此时,np.where函数取出x中所有非0数,生成一个新的数列。
__call__(x), 2) class ReLU(): def __call__(self, x): return np.where(x >= 0, x, 0) def gradient(self, x): return np.where(x >= 0, 1, 0) class LeakyReLU(): def __init__(self , alpha=0.2): self.alpha = alpha def __call__(self, x): return np.where(x >= 0, x, self.alpha * x) def gradient(self, x): return np.where(x >= 0, 1, self.alpha) class (x >= 0.0, x, self.alpha * (np.exp(x) - 1)) def gradient(self, x): return np.where(x >=
# cnt1 = len(np.where(msk >= 0)[0]) # cnt2 = len(np.where(msk == 0)[0]) # cnt3 = len(np.where format(cnt1, cnt2, cnt3)) # assert(cnt1 == cnt2 + cnt3) # 边缘模糊所以存在两者之间的像素 # # cnt1 = len(np.where (dilated >= 0)[0]) # cnt2 = len(np.where(dilated == 0)[0]) # cnt3 = len(np.where(dilated == 255 :{} bg:{} fg:{}".format(cnt1, cnt2, cnt3)) # assert(cnt1 == cnt2 + cnt3) # # cnt1 = len(np.where (eroded >= 0)[0]) # cnt2 = len(np.where(eroded == 0)[0]) # cnt3 = len(np.where(eroded == 255)
() result = np.where(cond, xarr, yarr) # np.where()的用法: ? #np.where()的几个例子 # condition, x, y均指定 np.where([[False, True], [True, False]], [[1, 2], [3, 4]], [[9, ) x[np.where( x > 3.0 )] # 将索引值带入原数组,得到满足大于3条件的元素 arr = np.random.normal(size=(4,4)) print(arr) np.where (arr > 0, 2, -2) np.where(arr > 0, 2, arr) # 只将大于0的元素设置为2 # 用np.where()进行多条件判断 # 例子: 对0~100范围内的数进行判断 5 result = np.where(cond1 & cond2, 3, np.where(cond1, 2, np.where(cond2 < 5, 1, -1))) print(sum(result
Pandas处理 这里通过df.where和np.where两个函数来实现需求,先看代码,然后我们再讲解下 import pandas as pd # 读取数据 df = pd.read_excel( (score<60,"不及格", np.where(score<90,"及格","高分"))) # 性别 data['性别'] = df['性别'].where(df['性别']>100, np.where 和Excel中IF函数更接近的其实就是np.where这个函数,如果条件满足则赋值x,否则赋值y。 我们就可以构建对科目评分进行评级的双层条件,具体如下: # 如果小于60就不及格,否则再进行后面的判断 np.where(score<60,"不及格", np.where(score<90,"及格"," (score<60,"不及格", np.where(score<90,"及格","高分"))) # 性别 data['性别'] = np.where(df['性别']==0, '女性', '男性')
(y==0),np.where(y==1) #可视化 plt.rc('font', size=14)#设置图中字号大小 plt.rcParams['font.sans-serif'] = 'SimHei (y==0),np.where(y==1) index_y2,index_y3=np.where(y==2),np.where(y==3) labels= kmeans.labels_ #提取聚类结果的类标签 #获取簇标签的索引,用于将样本按簇绘制 index_label0,index_label1=np.where(labels==0),np.where(labels==1) index_label2,index_label3 =np.where(labels==2),np.where(labels==3) #可视化原始数据类别与聚类结果,进行对比 p=plt.figure(figsize=(12,4)) #子图1:绘制原始类别数据 (X_yl[:,2]==0),np.where(X_yl[:,2]==1) index_2,index_3=np.where(X_yl[:,2]==2),np.where(X_yl[:,2]==3) X_yl1
主要使用的函数有,np.vstack, np.hstack, np.where, df.loc, heapq.nlargest。这几个方法的应用已经基本上满足矩阵处理的大部分需求。 img=np.atleast_2d(img) img1=img.copy() img1[np.where(img<100)]=200 cv2.imwrite("enhanced.jpg",img1) 二值化常用于目标检测,轮廓提取,或者其他应用 #二值化 img2=np.where(img>160,255,0) cv2.imwrite("binary.jpg",img2) ? np.where函数能够得到满足条件的index. np.where(trains[:,-1]==4) ? 从输出来看可以看到,第0行,7行,...299行的label等于4. np.where(trains==4) ? 可以看到返回了两个独立的数组,很明显第一个数组是坐标$X$,第二个数组是坐标$Y$。这样就能在二维空间中对某个特定值定位到具体的位置。
np.where np.where给定一个条件表达式,当条件表达式为真或假时返回对应的值。 %%timeit # Pandas Series Vectorized baby!! # you can pass the output directly into a pandas Series df['normalized_status'] = np.where( df[' ` is {round((8.15 * 1000) / 20.8, 1)}x faster than `.apply`") `np.where` is 391.8x faster than `.apply %%timeit df['lead_category'] = \ np.where(df['Original Record: Date Created'].values == df['Date 82.4 ms ± 865 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) np.select 和 np.where 的输出结果是相同的。
主要使用的函数有,np.vstack, np.hstack, np.where, df.loc, heapq.nlargest。这几个方法的应用已经基本上满足矩阵处理的大部分需求。 img=np.atleast_2d(img) img1=img.copy() img1[np.where(img<100)]=200 cv2.imwrite("enhanced.jpg",img1) 二值化常用于目标检测,轮廓提取,或者其他应用 #二值化 img2=np.where(img>160,255,0) cv2.imwrite("binary.jpg",img2) ? np.where函数能够得到满足条件的index. np.where(trains[:,-1]==4) ? 从输出来看可以看到,第0行,7行,...299行的label等于4. np.where(trains==4) ? 可以看到返回了两个独立的数组,很明显第一个数组是坐标$X$,第二个数组是坐标$Y$。这样就能在二维空间中对某个特定值定位到具体的位置。
参考链接: Python中的numpy.place 注意: df1.where(cond,df2) 等价于 np.where(cond, df1, df2) 1. pandas.DataFrame.where >>> import numpy as np >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.where 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> np.where ②如果参数只有condition的话,返回值是condition中元素值为true的位置索引,且是以元组形式返回,元组的元素是ndarray数组,表示位置的索引 >>> np.where([[True . [[9, 8], [7, 6]]) array([[1, 8], [3, 4]]) >>> x = np.arange(9).reshape(3, 3) >>> np.where
in zip(condition, x, y)]Examples>>> a = np.arange(10)>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> np.where )array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])This can be used on multidimensional arrays too:>>> np.where [3, 4]])The shapes of x, y, and the condition are broadcast together:>>> x, y = np.ogrid[:3, :4]>>> np.where [0, 3, 6]])>>> np.where(a < 4, a, -1) # -1 is broadcastarray([[ 0, 1, 2], [ 0
rt_raster_array[1]则表示取出第二个波段,在本文中也就是自有产品的QA波段;.GetRasterBand(1)表示获取栅格图像中的第一个波段(注意,这里序号不是从0开始而是从1开始);np.where (rt_lai_array>30000,np.nan,rt_lai_array)表示利用np.where()函数对Array中第一个波段中像素>30000加以选取,并将其设置为nan,其他值不变。 ((rt_qa_array_bin>=100) & (rt_qa_array_bin==11)) # eco_pixel_pos=np.where((rt_qa_array_bin plt.title("Difference_LAI (RT-GLASS)") # plt.colorbar() DRT_lai_dif_array=np.where ((rt_qa_array_bin>=100) & (rt_qa_array_bin==11)) # eco_pixel_pos=np.where((rt_qa_array_bin
通过np.max和np.where通过np.max()找矩阵的最大值,再通过np.where获得最大值的位置,测试如下:a = np.random.randint(10, 100, size=9)a = a.reshape((3,3))print(a)r, c = np.where(a == np.max(a))print(r,c)代码分析:首先,我们导入了NumPy库并为其分配了别名np。 代码r, c = np.where(a == np.max(a))的作用是找到数组a中的最大值,并确定该最大值所在的行和列。 np.max(a)返回数组a中的最大值,然后np.where(a == np.max(a))返回一个包含最大值位置索引的元组。这个元组被解包给了变量r和c,其中r表示行索引,c表示列索引。 通过使用np.where()函数,可以一次性找到数组中所有满足条件的元素的位置,而不仅仅是最大值。代码逻辑简单明了,易于理解和实现。
, 0])top_point_y = np.min(box[:, 1])bottom_point_y = np.max(box[:, 1]) left_point_y = box[:, 1][np.where (box[:, 0] == left_point_x)][0]right_point_y = box[:, 1][np.where(box[:, 0] == right_point_x)][0]top_point_x = box[:, 0][np.where(box[:, 1] == top_point_y)][0]bottom_point_x = box[:, 0][np.where(box[:, 1] == bottom_point_y
使用 np.where 使用np.where(): np.where(判断条件,为真时的处理,为假时的处理) x = np.where(x%2==1, x+1, x) 3.
df["分"] = df["time1"].dt.minute df["秒"] = df["time1"].dt.second df["flag"] = df["日"] df["xun"] = np.where ((df["flag"] > 10) & (df["flag"] <= 20), "中旬", np.where(df["flag"] <= 10, "上旬", "下旬")) print("\n") print df["日"] = df["time1"].dt.day获取日期对应的具体几号 df["xun"] = np.where((df["flag"] > 10) & (df["flag"] <= 20), "中旬", np.where(df["flag"] <= 10, "上旬", "下旬")),两重判断 np.where(条件,满足条件结果,不满足条件结果) 支持嵌套,有点VBA公式的感觉 对flag列的每个元素进行计算