Skip to content
Advertisement

pandas assign across multiple columns functionally

Is there a way, in pandas, to apply a function to some chosen columns, while strictly keeping a functional pipeline (no border effects,no assignation before the result, the result of the function only depends of its arguments, and I don’t want to drop the other columns). Ie, what is the equivalent of across in R ?

JavaScript

In R, I would have written :

JavaScript

Advertisement

Answer

One option is to unpack the computation within assign:

JavaScript

For readability purposes, I’d suggest splitting it up:

JavaScript

Another option, still with the unpacking idea is to iterate through the columns, based on the pattern:

JavaScript

You can dump it into a function and then pipe it:

JavaScript

We can take the function declaration a step further for easier use :

JavaScript

pyjanitor has a transform_columns function that can be handy for this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement