def run(self, table): """ :returns: :class:`decimal.Decimal` """ # If the user has provided a total, use that if self._total is not None: total = self._total # Otherwise compute the sum of all the values in that column to # act as our denominator else: total = table.aggregate(Sum(self._column_name)) # Raise error if sum is less than or equal to zero if total <= 0: raise DataTypeError( 'The sum of column values must be a positive number') # Create a list new rows new_column = [] # Loop through the existing rows for row in table.rows: # Pull the value value = row[self._column_name] if value is None: new_column.append(None) continue # Try to divide it out of the total percent = value / total # And multiply it by 100 percent = percent * 100 # Append the value to the new list new_column.append(percent) # Pass out the list return new_column
def __init__(self, column_name): self._column_name = column_name self._sum = Sum(column_name)