So for the same thing
data.loc[:,data.isin([0,1]).all()]
does for a panda dataframe. I want to know how to do this when it is a ndarray?
1 40 0 0 0 0 0 0
2 58 0 0 1 0 0 0
3 41 0 1 1 0 0 1
4 45 0 0 1 1 0 1
5 60 0 1 0 1 0 1
def checkBinary(data):
getBinaryCol = data.loc[:,data.isin([0,1]).all()]
if i in getBinaryCol:
return True
else:
return False
This is the function for pandas dataframe how do i change getBinaryCol if passing data.values(ndarray) instead of only data?
CodePudding user response:
The code below checks if each cell contains either 0
's or 1
's, allows both by using np.logical_or
and checks if the condition is met for the whole column by using np.all
.
mat = np.array(
[[ 3, 0, 1, 1, 0],
[ 5, 1, 4, 0, 0],
[ 8, 0, 0, 0, 0]]
)
def is_col_bin(mat, i):
return np.all(np.logical_or(mat[...,i] == 0, mat[...,i] == 1))
print([is_col_bin(mat, i) for i in range(mat.shape[-1])])
# [False, True, False, True, True]