Subtract values of single row polars frame from multiple row polars frame

Question:

Lets say I have a polars dataframe like this in python

    newdata = pl.DataFrame({
        'A': [1, 2, 3, 4],
        'B': [5, 6, 7, 8],
        'C': [9, 10, 11, 12],
        'D': [13, 14, 15, 16]
    })

And I want to subtract from every value in every column the corresponding value from another frame

baseline = pl.DataFrame({
    'A': [1],
    'B': [2],
    'C': [3],
    'D': [4]
})

In pandas, and numpy, the baseline frame is automagically broadcasted to the size of the newdata, and I can just do;

data=newdata-baseline

But that doesn’t work in polars. So what is the cleanest way to achieve this in polars?

Asked By: visibleman

||

Answers:

Here loop by column names can be used:

newdata.with_columns(
    [pl.col(c) - baseline[c] for c in newdata.columns]
)
Answered By: glebcom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.