Skip to content
Advertisement

Cleaner way to selectively multiply pandas DataFrame values

Given this example:

JavaScript

Where the values in df are multiplied by non-NaN values from factors, is there a cleaner way to do this with pandas? (or numpy for that matter) I had a look at .mul(), but that doesn’t appear to allow me to do what’s required here.

Additionally, what if factors contains rows with an id that’s not in df, e.g.:

JavaScript

Advertisement

Answer

If I understand your problem right, you can use .update + .mul:

JavaScript

Prints:

JavaScript

For the second example (if factors contains rows with an id that’s not in df) this prints:

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