I have a pandas frame with several measurements for a number of samples. E.g. measuring temperature, length, and width of multiple widgets.
I also have a frame with the acceptable limits for each type of measurements. I need to apply both low and high limits to the measurements and return a frame that has the low limit subtracted from the measurement and the measurement subtracted from the high limit. I.e. for each column in the measurement table I should get back two columns, and the number of rows in the output is the same as the number of rows in the input
Here is a toy example:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[30,40,50]})
limits = pd.DataFrame({'col':['a','b'], 'low':[1,10], 'high':[10,100]})
What I was able to come up with almost does the job, expect it appends the low and high limit applied columns along axis= 0 instead of axis=1
import pandas as pd
def apply_limits(col):
temp = limits[limits.col == col.name]
return pd.concat([col - temp.low.values[0], col - temp.high.values[0]])
df = pd.DataFrame({'a':[1,2,3], 'b':[30,40,50]})
limits = pd.DataFrame({'col':['a','b'], 'low':[1,10], 'high':[10,100]})
df.apply(apply_limits)
returns
a b
0 0 20
1 1 30
2 2 40
0 9 70
1 8 60
2 7 50
I get what I need if I do
temp = df.apply(apply_limits)
pd.concat([temp.iloc[:3], temp.iloc[3:]], axis = 1)
a b a b
0 0 20 9 70
1 1 30 8 60
2 2 40 7 50
I wonder if there is a more elegant way of doing it.