AZhao
AZhao

Reputation: 14405

Modifying Pandas DF Class outside of Class?

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.

Upvotes: 0

Views: 109

Answers (1)

JoeCondron
JoeCondron

Reputation: 8906

You can do

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

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

Upvotes: 1

Related Questions