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?
Answers:
Here loop by column names can be used:
newdata.with_columns(
[pl.col(c) - baseline[c] for c in newdata.columns]
)
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?
Here loop by column names can be used:
newdata.with_columns(
[pl.col(c) - baseline[c] for c in newdata.columns]
)