大熊猫根据列值遍历行

时间:2020-09-02 23:16:05

标签: pandas loops

我想同时计算到城市之间的温度差。数据结构如下:

dic = {'city':['a','a','a','a','a','b','b','b','b','b'],'week':[1,2,3,4,5,3,4,5,6,7],'temp':[20,21,23,21,25,20,21,24,21,22]}
df = pd.DataFrame(dic)
df
+------+------+------+
| city | week | temp |
+------+------+------+
| a    |    1 |   20 |
| a    |    2 |   21 |
| a    |    3 |   23 |
| a    |    4 |   21 |
| a    |    5 |   25 |
| b    |    3 |   20 |
| b    |    4 |   21 |
| b    |    5 |   24 |
| b    |    6 |   21 |
| b    |    7 |   22 |
+------+------+------+

我想计算第3、4和5周的城市a和b之间的温度差。最终数据结构应如下所示:

+--------+-------+------+------+
| city_1 | city2 | week | diff |
+--------+-------+------+------+
| a      | b     |    3 |    3 |
| a      | b     |    4 |    0 |
| a      | b     |    5 |    1 |
+--------+-------+------+------+

1 个答案:

答案 0 :(得分:1)

我将透视数据,删除NA值,然后直接进行减法。这样,您可以保持与每个城市相关的源温度。

result = (
    df.pivot(index='week', columns='city', values='temp')
      .dropna(how='any', axis='index')
      .assign(diff=lambda df: df['a'] - df['b'])  
)
print(result)
city     a     b  diff
week                  
3     23.0  20.0   3.0
4     21.0  21.0   0.0
5     25.0  24.0   1.0