如果高于平均值,则减少 pandas 系列值

Decrease pandas series value if it is higher than the mean

我正试图将我的 pandas 系列中高于平均值的所有记录的值降低 2.5%。

我想用update方法解决问题

price_per_city = {
    "Bragança": 10.3,
    "Braga": 10.6,
    "Porto": 11.5,
    "Aveiro": 12.3,
    "Coimbra": 9.9,
    "Leiria": 9.3,
    "Lisboa": 12.1,
    "Beja": 10.9,
    "Évora": 11.4,
    "Faro": 9.1
}

prcSerie = pd.Series(price_per_city)
prcSerie.update(prcSerie, prcSerie[prcSerie >=prcSerie.mean()])
print(prcSerie)

试试 where:

prcSerie = prcSerie.where(prcSerie.le(prcSerie.mean()), prcSerie.mul(0.975))

>>> prcSerie
Bragança    10.3000
Braga       10.6000
Porto       11.2125
Aveiro      11.9925
Coimbra      9.9000
Leiria       9.3000
Lisboa      11.7975
Beja        10.6275
Évora       11.1150
Faro         9.1000
dtype: float64

使用 update 进行就地修改:

prcSerie.update(prcSerie.loc[prcSerie>=prcSerie.mean()].mul(0.975).round(2))

输出:

Bragança    10.30
Braga       10.60
Porto       11.21
Aveiro      11.99
Coimbra      9.90
Leiria       9.30
Lisboa      11.80
Beja        10.63
Évora       11.12
Faro         9.10
dtype: float64