numpy ndarray 取出满足特定条件的某些行实例

yipeiwu_com5年前Python基础

在进行物体检测的ground truth boxes annotations包围框坐标数据整理时,需要实现这样的功能:

numpy里面,对于N*4的数组,要实现对于每一行,如果第3列和第1列数值相等或者第2列和第0列数值相等,就删除这一行,要返回保留下来的numpy数组 shape M*4

对于numpy数组的操作要尽量避免for循环,因为numpy数组支持布尔索引。

import numpy as np

a1=np.array(
  [1,0,1,5]
)
a2=np.array(
  [0,8,5,8]
)
center=np.random.randint(0,10,size=(3,4))
# print(a1.shape,a2.shape,center.shape)
b=np.vstack((a1,center,a2))
'''

numpy vstack 所输入的参数必须是list或者tuple的iterable对象,在竖直方向上进行数组拼接

其中list或者tuple中的每个元素是numpy.ndarray类型

它们必须具有相同的列数,拼接完成后行数增加

numpy hstack 在水平方向上进行数组拼接

进行拼接的数组必须具有相同的行数,拼接完成后列数增加

'''
print(b.shape,b)
out=b[b[:,3]!=b[:,1]]
out2=out[out[:,2]!=out[:,0]]
print(out2.shape,out2)
'''
(5, 4) 
[[1 0 1 5]
 [6 9 9 1]
 [9 1 6 5]
 [2 8 8 1]
 [0 8 5 8]]
(3, 4) 
[[6 9 9 1]
 [9 1 6 5]
 [2 8 8 1]]
'''
b1=a1.reshape(-1,1)
b2=a2.reshape(-1,1)
before_list=[]
before_list.append(b1)
before_list.append(center.reshape(4,3))
before_list.append(b2)
out3=np.hstack(before_list)
print(out3.shape)#(4, 5)

以上这篇numpy ndarray 取出满足特定条件的某些行实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用Python发送邮件附件以定时备份MySQL的教程

最近迁移了wordpress,系统升级为CentOS 6,很奇怪的一个问题,在原来CentOS 5.8下用的很正常的定时备份数据库并通过邮件发送的脚本不能发送附件,其他都正常,邮件内容也...

python使用matplotlib绘制折线图教程

python使用matplotlib绘制折线图教程

matplotlib简介 matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图。而且也可以方便地将它作为绘图控件,嵌入...

python打包压缩、读取指定目录下的指定类型文件

下面通过代码给大家介绍python打包压缩指定目录下的指定类型文件,具体代码如下所示: import os import datetime import tarfile import...

python 列表中[ ]中冒号‘:’的作用

中括号[ ]:用于定义列表或引用列表、数组、字符串及元组中元素位置 list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1,...

Python的Flask开发框架简单上手笔记

最简单的hello world #!/usr/bin/env python # encoding: utf-8 from flask import Flask app = Fla...