最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How to calculate with MultIndex? - Stack Overflow

programmeradmin0浏览0评论

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
  • Well, thinking a little bit more in detaill I found a solution: df.query('T==125')-df.query('T==25') – Christof Bodner Commented Nov 20, 2024 at 15:25
  • 1 Actually 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
Add a comment  | 

1 Answer 1

Reset to default 2

Select 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}]
发布评论

评论列表(0)

  1. 暂无评论