0

Is it possible to modify a class outside of a class?

I frequently have to add a new column to my data frames and am looking for cleaner syntax. All my dataframes come ready for this operation.

It's essentially this operation:

DF['Percent'] = float(DF['Earned'])/DF['Total']

I'd love to add this functionality like so:

DF = DF.add_percent()

Or DF.add_percent(inplace=True)

Right now I'm only able to do something like:

DF = add_percent(DF)

where I declare add_percent as a function outside of pandas.

AZhao
  • 13,617
  • 7
  • 31
  • 54
  • possible duplicate of [Python: changing methods and attributes at runtime](http://stackoverflow.com/questions/962962/python-changing-methods-and-attributes-at-runtime). See also: http://stackoverflow.com/q/962962/1560062, http://stackoverflow.com/q/972/1560062 – zero323 Aug 17 '15 at 20:37
  • Maybe [this](http://stackoverflow.com/questions/25465120/convert-a-user-function-to-be-a-dataframe-method-or-equivalent) as a DataFrame-specific duplicate? – DSM Aug 17 '15 at 20:45

1 Answers1

1

You can do

DF.eval('Percent = Earned / Total')

I don't think it gets much cleaner than that.

JoeCondron
  • 8,546
  • 3
  • 27
  • 28