简体   繁体   English

Python:在多个数组列中计数零并有效地存储它们

[英]Python: Counting Zeros in multiple array columns and store them efficently

I create an array:我创建一个数组:

import numpy as np
arr = [[0, 2, 3], [0, 1, 0], [0, 0, 1]]
arr = np.array(arr)

Now I count every zero per column and store it in a variable:现在我计算每列的每个零并将其存储在一个变量中:

a = np.count_nonzero(arr[:,0]==0)
b = np.count_nonzero(arr[:,1]==0)
c = np.count_nonzero(arr[:,2]==0)

This code works fine.此代码工作正常。 But in my case I have many more columns with over 70000 values in each.但在我的情况下,我有更多的列,每个列都有超过 70000 个值。 This would be many more lines of code and a very messy variable expolorer in spyder.这将是更多的代码行和 spyder 中一个非常混乱的变量探索器。

My questions:我的问题:

  1. Is there a possibility to make this code more efficient and save the values only in one type of data, eg a dictionary, dataframe or tuple?是否有可能使此代码更高效并仅将值保存在一种类型的数据中,例如字典、dataframe 或元组?
  2. Can I use a loop for creating the dic, dataframe or tuple?我可以使用循环来创建 dic、dataframe 或元组吗?

Thank you谢谢

You can construct a boolean array arr == 0 and then take its sum along the rows.您可以构造一个 boolean 数组arr == 0 ,然后沿行取其总和。

>>> (arr == 0).sum(0)
array([3, 1, 1])

Use an ordered dict from the collections module:使用 collections 模块中的有序字典:

from collections import OrderedDict
import numpy as np
from pprint import pprint as pp
import string

arr = np.array([[0, 2, 3], [0, 1, 0], [0, 0, 1]])
letters = string.ascii_letters
od = OrderedDict()

for i in range(len(arr)):
    od[letters[i]] = np.count_nonzero(arr[:, i]==0)

pp(od)

Returning:返回:

OrderedDict([('a', 3), ('b', 1), ('c', 1)])

Example usage:示例用法:

print(f"First number of zeros: {od.get('a')}")

Will give you:会给你:

First number of zeros: 3

To count zeros you can count non-zeros along each column and subtract result from length of each column:要计算零,您可以沿每列计算非零并从每列的长度中减去结果:

arr.shape[0] - np.count_nonzero(arr, axis=0)

produces [3,1,1] .产生[3,1,1]

This solution is very fast because no extra large objects are created.这个解决方案非常快,因为没有创建额外的大对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM