I have a Pandas DataFrame with coordinates values (X,Y), temperatures (T) and measurement results (H)
df=pd.DataFrame([
{'X':0,'Y':0,'T':25,'H':1.2},
{'X':1,'Y':0,'T':25,'H':1.3},
{'X':0,'Y':1,'T':25,'H':1.4},
{'X':1,'Y':1,'T':25,'H':1.5},
{'X':0,'Y':0,'T':125,'H':2.2},
{'X':1,'Y':0,'T':125,'H':2.4},
{'X':0,'Y':1,'T':125,'H':2.6},
{'X':1,'Y':1,'T':125,'H':2.8},
])
df=df.set_index(['X','Y','T'])
Now I would like to calculate the difference of the measurements at the temperatures of each coordinate point: H(T=125)-H(T=25) So I would like to get
{'X':0,'Y':0,'dH':1.0}
{'X':1,'Y':0,'dH':1.1}
{'X':0,'Y':1,'dH':1.2}
{'X':1,'Y':1,'dH':1.3}
How to do this in a pythonic way?
I have a Pandas DataFrame with coordinates values (X,Y), temperatures (T) and measurement results (H)
df=pd.DataFrame([
{'X':0,'Y':0,'T':25,'H':1.2},
{'X':1,'Y':0,'T':25,'H':1.3},
{'X':0,'Y':1,'T':25,'H':1.4},
{'X':1,'Y':1,'T':25,'H':1.5},
{'X':0,'Y':0,'T':125,'H':2.2},
{'X':1,'Y':0,'T':125,'H':2.4},
{'X':0,'Y':1,'T':125,'H':2.6},
{'X':1,'Y':1,'T':125,'H':2.8},
])
df=df.set_index(['X','Y','T'])
Now I would like to calculate the difference of the measurements at the temperatures of each coordinate point: H(T=125)-H(T=25) So I would like to get
{'X':0,'Y':0,'dH':1.0}
{'X':1,'Y':0,'dH':1.1}
{'X':0,'Y':1,'dH':1.2}
{'X':1,'Y':1,'dH':1.3}
How to do this in a pythonic way?
Share Improve this question edited Nov 20, 2024 at 19:27 wjandrea 33.2k10 gold badges69 silver badges98 bronze badges asked Nov 20, 2024 at 15:20 Christof BodnerChristof Bodner 394 bronze badges 2 |1 Answer
Reset to default 2Select with xs
and compute the difference:
df.xs(125, level='T').sub(df.xs(25, level='T'))
Output:
H
X Y
0 0 1.0
1 0 1.1
0 1 1.2
1 1 1.3
As list of dictionaries:
(df.xs(125, level='T').sub(df.xs(25, level='T'))
.round(2).reset_index().to_dict('records')
)
Output:
[{'X': 0, 'Y': 0, 'H': 1.0},
{'X': 1, 'Y': 0, 'H': 1.1},
{'X': 0, 'Y': 1, 'H': 1.2},
{'X': 1, 'Y': 1, 'H': 1.3}]
df.query('T==125')-df.query('T==25')
should not work (unless you drop the level) since the indices won't align. – mozway Commented Nov 20, 2024 at 15:29