如果满足两个条件,则计算平均值

时间:2017-05-08 11:27:38

标签: python pandas conditional mean

设置向上

我正在使用Scrapy抓取住房广告,然后用熊猫分析数据。

我使用熊猫来计算几种房屋特征的均值和中位数。

数据框df看起来像,

district | rent | rooms | …
----------------------------
 North   | 200  |   3   | …
 South   | 300  |   1   | …
 South   | 300  |   1   | …
   ⋮         ⋮       ⋮     ⋮

问题

我想计算每个区 n - 房间公寓的平均租金。

我找到了一个让我接近的答案here,例如

df.loc[df['rooms'] == 1, 'rent'].mean()

但这计算了整个城市的单卧室公寓的平均租金。

要按区域进行,我想做类似的事情,

for d in district_set:
     df.loc[df['rooms'] == 1 and df['district'] == d, 'rent'].mean()

其中district_set包含所有可能的区域。

有什么建议吗?

我想获得下表,

district | avg rent 1R | avg rent 2R | …
----------------------------------------
 North   |     200     |     400     | …
 South   |     300     |     500     | …
   ⋮            ⋮              ⋮

0 个答案:

没有答案
相关问题