Reputation: 265
I imported a csv file with the variable “HEIGHT” which has 10 values.
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. The answer should be 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.
Upvotes: 0
Views: 824
Reputation: 1744
If you want to use numpy and numpy only,
Load the file using numpy:
dataset = np.loadtxt('measurements.csv', delimiter=',')
Seems like the height variable is in the 3rd column (index 2). When you use loadtxt
, you'll get a 2D array that looks like a table. You need the column with index 2, and you can then use @tom10's solution:
(dataset[:, 2] != 62).sum()
And you have a complete numpy workflow.
Note: Read docs to understand functions used better.
Upvotes: 1
Reputation: 69182
Using numpy you can do:
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.
Upvotes: 2