Search code examples
pythoncsvbinarymultiplicationpython-itertools

Python: How to do looping multiplication and discard those binary value 0?


I have binary values filled in a csv file and a list of real number values that I would like to apply multiplication on both files. How can I discard those values which multiply with the value of 0 in csv file? Can anyone help me with the algorithm part?

Binary.csv

This is 3 lines binary values.

0 1 0 0 1 0 1 0 0 
1 0 0 0 0 1 0 1 0
0 0 1 0 1 0 1 0 0

Real.csv

This is one line real number values.

0.1 0.2 0.4 0.1 0.5 0.5 0.3 0.6 0.3

Before desired output

0.0 0.2 0.0 0.0 0.5 0.0 0.3 0.0 0.0
0.1 0.0 0.0 0.0 0.0 0.5 0.0 0.6 0.0 
0.0 0.0 0.4 0.0 0.5 0.0 0.3 0.0 0.0

Desired output

0.2 0.5 0.3
0.1 0.5 0.6
0.4 0.5 0.3

Code

import numpy as np
import itertools

a = np.array([[0,1,0,0,1,0,1,0,0],[1,0,0,0,0,1,0,1,0],[0,0,1,0,1,0,1,0,0]])
b = np.array([0.1,0.2,0.4,0.1,0.5,0.5,0.3,0.6,0.3])
c=(a * b)

d=itertools.compress(c,str(True))
print d

The above code is just another alternatives that I tried at the same time. Sorry for inconvenience. Very appreciate all your helps here.


Solution

  • Several ways to do this, mine is simplistic:

    import csv
    
    with open('real.csv', 'rb') as csvfile:
        for row in csv.reader(csvfile, delimiter=' '):
            reals = row
    
    with open('binary.csv', 'rb') as csvfile:
        pwreader = csv.reader(csvfile, delimiter=' ')
    
        for row in pwreader:
            result = []
            for i,b in enumerate(row):
                if b == '1' :
                    result.append(reals[i])
    
            print " ".join(result)
    

    You will notice that there is no multiplication here. When you read from a CSV file the values are strings. You could convert each field to a numeric, construct a bit-mask, then work it out from there, but is it worth it? I have just used a simple string comparison. The output is a string anyway.

    Edit: now I find you have numpy arrays in your code, ignoring the csv files. Please stop changing the goalposts!