How to apply math operations to a row of a csv in python?
Question: I've been successful creating functions in python and reading/writing files.
However, I really need to apply certain functions to whole **rows** of data
(**not columns**) and can't find out anything about how to do this. The goals
are:

  * Read a csv or txt file into python (can-do)
  * Find a row of data and apply certain conditions and operations
  * Do the same with a second row of data
  * Then compare results from the rows to each other (done with a similarity function)
  * Print the resulting data into a separate file (easy peasy)

Function parameters include "if/then" conditions for ratios, sums, and square
roots -- will not include whole function. For example, just use sum

Here's what I have so far (not much...):

    
    
    import numpy as np
    data = np.genfromtxt ('file_to_read.csv', 
                           dtype=float,
                           delimiter=",",
                           names=True)
    np.sum()
    print(data)
    np.savetxt('test.csv', data, delimiter=',')
    

file_to_read.csv is this:

    
    
    0,2,1
    0,2,2
    0,2,3
    0,1,0
    0,2,0
    0,3,0
    1,0,0
    2,0,0
    3,0,0
    


Answer: you can transpose your matrix or data frame (if using pandas) and work with
columns.

Example (pandas):

Original DF

    
    
    In [162]: df
    Out[162]:
       a  b  c
    0  0  2  1
    1  0  2  2
    2  0  2  3
    3  0  1  0
    4  0  2  0
    5  0  3  0
    6  1  0  0
    7  2  0  0
    8  3  0  0
    

Transposed DF

    
    
    In [163]: df.T
    Out[163]:
       0  1  2  3  4  5  6  7  8
    a  0  0  0  0  0  0  1  2  3
    b  2  2  2  1  2  3  0  0  0
    c  1  2  3  0  0  0  0  0  0
    

Select rows where `b>0` and `c>1`:

    
    
    In [166]: df[(df.b>0) & (df.c>1)]
    Out[166]:
       a  b  c
    1  0  2  2
    2  0  2  3
    

now calculate sum of cells for each found row:

    
    
    In [167]: df[(df.b>0) & (df.c>1)].sum(axis=1)
    Out[167]:
    1    4
    2    5
    dtype: int64
    

or product:

    
    
    In [169]: df[(df.b>0) & (df.c>1)].product(axis=1)
    Out[169]:
    1    0
    2    0
    dtype: int64
    

PS using `axis=1` instructs Pandas/Numpy to use rows instead of columns

