Skip to content Skip to sidebar Skip to footer

Python: Pandas, Parsing Math Operations

somebody on stackoverflow adviced me to use pandas to label the values of my csv files and provided the code below: # original code import pandas cmf = pandas.read_csv('CMF_MA68II

Solution 1:

This will do that calculation into three new columns, then group by the name and serial number (you could actually group by either in this case, but this way you get both in the final result):

# First calculate the new columns
cols = ['x', 'y', 'z']
uppercols = ['X', 'Y', 'Z']
for uppercol, col in zip(uppercols, cols):
    merged[uppercol] = (merged[col] * merged.a * merged.measurement)/totals['y']

# Now group and sum
sums = merged.groupby(['serialNumber', 'name'])[uppercols].sum()

To write that to a CSV file, just do

sums.to_csv('test.csv')

Solution 2:

You can group and apply an user-defined function:

res =  merged.groupby(['serialNumber','name']).apply(lambda g:pd.Series([(g[c] * g.a * g.measurement).sum() / totals['y'] for c in"xyz"], index=['X','Y','Z']))
print res

Post a Comment for "Python: Pandas, Parsing Math Operations"