Reputation: 1
Write a function calc_frac(a,axis=0) that takes a 2-dimensional numpy array containing only zeros and ones and returns an array giving the fraction of ones in each column (if axis=0) or in each row (if axis=1).
This is what I have so far
import numpy as np
a = np.array([[1,0,1],[1,1,0],[0,1,0]])
b = np.zeros((3,1))
col_r1 = a[:,0:1]
col_r2 = a[:,1:2]
col_r3 = a[:,2:3]
i=0
j=0
k=0
for i in col_r1:
if i >= 1:
i = i+1
b[0]= i/3
for k in col_r2:
if k >= 1:
k=k+1
b[1] = k/3
for f in col_r3:
if f >= 1:
f=f+1
b[2] = f/3
print(b)
print(col_r3)
Here are the problems I have:
If you print b after all the mutations it shows b[2] as 0.6667 instead of 0.333. since the column should have only 1 copy of the number 1
I'm not sure how I could rewrite this code as a function in the format shown above in the question.
As I'm not familiar with numpy I was wondering if there was a way to write a code that does the same function without using for loops.
Thanks in advance
Upvotes: 0
Views: 167
Reputation: 95873
def calc_frac(a, axis=0):
return a.mean(axis=axis)
The key is that the mean of an array of ones and zeros is the fraction of 1's.
Upvotes: 1