有条件地替换熊猫系列的值

时间:2021-03-17 12:26:19

标签: python python-3.x pandas

我必须编写一个函数来替换熊猫系列中较小的所有值 比 a 由系列的平均值。系列和数字 a 应该是 函数的参数。 例如,如果系列是 [10,11,12,3,4,5,7,9,15,20] ,并且 a = 7,则 结果系列应为 [10.0,11.0,12.0,9.6,9.6,9.6,7.0,9.0,15.0,20.0]

我想知道如何使用 series.replace 函数用平均值替换低于平均值的值 到目前为止我写的代码是:

import pandas as pd

def ex1(L,a):
    #Creating the Series 
    sr = pd.Series(L)
    result = sr.mean()
#replace values < the mean by the value of the mean
    sr.replace(to_replace=<9.6, value=result)

1 个答案:

答案 0 :(得分:0)

使用loc索引直接更新值。

sr.loc[sr<7] = sr.mean()

所以你的最终功能是

def ex1(L,a):
    sr = pd.Series(L)
    #replace values < the mean by the value of the mean
    sr.loc[sr<a] = sr.mean()
    return sr

另外你的函数没有返回,我假设你想返回。