简体   繁体   English

如何使用python计算变量中的出现次数

[英]How to count the number of occurrences in a variable using python

I imported a csv file with the variable “HEIGHT” which has 10 values.我导入了一个带有变量“HEIGHT”的 csv 文件,它有 10 个值。

HEIGHT
62
58
72
63
66
62
63
62
62
67

I want to use numpy and numpy only to count the number of times the value '62' does not occur.我只想使用 numpy 和 numpy 来计算值 '62' 不出现的次数。 The answer should be 6.答案应该是6。

import numpy
import csv
with open(‘measurements.csv’),’r’) as f:
rows=f.readline()
rows=f.split(‘,’)
rows=numpy.array([rows[2:4]])
print(rows)

I'm a beginner python learner practicing numpy, so I am not quite sure how to approach this problem.我是一个练习 numpy 的 Python 初学者,所以我不太确定如何解决这个问题。

Using numpy you can do:使用 numpy 你可以这样做:

data = np.array([62, 58, 72, 63, 66, 62, 63, 62, 62, 67])

(data != 62).sum()

That is, data != 62 will make a numpy Boolean array, and sum will add these up, with True as 1 , giving the total count.也就是说, data != 62将创建一个 numpy 布尔数组, sum会将这些sumTrue1 ,给出总数。

If you want to use numpy and numpy only ,如果您只想使用numpy 和 numpy

Load the file using numpy:使用 numpy 加载文件:

dataset = np.loadtxt('measurements.csv', delimiter=',')

Seems like the height variable is in the 3rd column (index 2 ).似乎高度变量在第三列(索引2 )中。 When you use loadtxt , you'll get a 2D array that looks like a table.当您使用loadtxt ,您将获得一个看起来像表格的二维数组。 You need the column with index 2, and you can then use @tom10's solution:您需要索引为 2 的列,然后您可以使用@tom10 的解决方案:

(dataset[:, 2] != 62).sum()

And you have a complete numpy workflow.你有一个完整的 numpy 工作流程。

Note: Read docs to understand functions used better.注意:阅读文档以更好地了解使用的函数。

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

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