python 判断矩阵中每行非零个数的方法

yipeiwu_com5年前Python基础

如下所示:

# -*- coding: utf-8 -*-
# @Time  : 2018/5/17 15:05
# @Author : Sizer
# @Site  : 
# @File  : test.py
# @Software: PyCharm
import time
import numpy as np

# data = np.array([
# [5.0, 3.0, 4.0, 4.0, 0.0],
# [3.0, 1.0, 2.0, 3.0, 3.0],
# [4.0, 3.0, 4.0, 3.0, 5.0],
# [3.0, 3.0, 1.0, 5.0, 4.0],
# [1.0, 5.0, 5.0, 2.0, 1.0]
# ])
data = np.random.random((1000, 1000))
print(data.shape)
start_time = time.time()
# avg = [float(np.mean(data[i, :])) for i in range(data.shape[0])]
# print(avg)


start_time = time.time()
avg = []
for i in range(data.shape[0]):
  sum = 0
  cnt = 0
  for rx in data[i, :]:
   if rx > 0:
     sum += rx
     cnt += 1
  if cnt > 0:
   avg.append(sum/cnt)
  else:
   avg.append(0)
end_time = time.time()
print("op 1:", end_time - start_time)

start_time = time.time()
avg = []
isexist = (data > 0) * 1
for i in range(data.shape[0]):
  sum = np.dot(data[i, :], isexist[i, :])
  cnt = np.sum(isexist[i, :])
  if cnt > 0:
   avg.append(sum / cnt)
  else:
   avg.append(0)
end_time = time.time()
print("op 2:", end_time - start_time)
#
# print(avg)
factor = np.mat(np.ones(data.shape[1])).T
# print("facotr :")
# print(factor)
exist = np.mat((data > 0) * 1.0)
# print("exist :")
# print(exist)
# print("res  :")
res = np.array(exist * factor)
end_time = time.time()
print("op 3:", end_time-start_time)

start_time = time.time()
exist = (data > 0) * 1.0
factor = np.ones(data.shape[1])
res = np.dot(exist, factor)
end_time = time.time()
print("op 4:", end_time - start_time)

经过多次验证, 第四种实现方式的事件效率最高!

以上这篇python 判断矩阵中每行非零个数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用celery实现异步任务执行的例子

使用celery在django项目中实现异步发送短信 在项目的目录下创建celery_tasks用于保存celery异步任务。 在celery_tasks目录下创建config.py文件...

python 获取utc时间转化为本地时间的方法

方法一: import datetime timenow = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))...

python 抓包保存为pcap文件并解析的实例

首先是抓包,使用scapy模块, sniff()函数 在其中参数为本地文件路径时,操作为打开本地文件 若参数为BPF过滤规则和回调函数,则进行Sniff,回调函数用于对Sniff到的数据...

Python使用turtle库绘制小猪佩奇(实例代码)

Python使用turtle库绘制小猪佩奇(实例代码)

turtle(海龟)是Python重要的标准库之一,它能够进行基本的图形绘制。turtle图形绘制的概念诞生于1969年,成功应用于LOGO编程语言。 turtle库绘制图形有一个基本...

Python程序设计入门(3)数组的使用

1、Python的数组可分为三种类型: (1) list 普通的链表,初始化后可以通过特定方法动态增加元素。定义方式:arr = [元素] (2) Tuple 固定的数组,一旦定义后,其...