【问题标题】:Python - Remove row if item is above certain value and replace if between other valuesPython - 如果项目高于某个值,则删除行并在其他值之间替换
【发布时间】:2021-09-23 18:14:00
【问题描述】:

我正在使用 pandas 数据框尝试清理一些数据,并且我想将多个规则分配给某个列。如果列值大于 500,我想删除该列。如果列值介于 101 和 500 之间,我想将值替换为 100。当列小于 101 时,返回列值。

我可以在 2 行代码中完成,但我很好奇是否有更清洁、更有效的方法来执行此操作。我尝试使用 If/Elif/Else,但我无法让它运行或 lambda 函数,但我再次无法让它运行。

# This drops all rows that are greater than 500
df.drop(df[df.Percent > 500].index, inplace = True)

# This sets the upper limit on all values at 100
df['Percent'] = df['Percent'].clip(upper = 100)

【问题讨论】:

    标签: python pandas if-statement clip


    【解决方案1】:

    您可以使用带有布尔掩码的.loc 代替带有索引的.drop() 并使用快速numpy 函数numpy.where() 来实现更高效/更好的性能,如下所示:

    import numpy as np
    
    df2 = df.loc[df['Percent'] <= 500]
    df2['Percent'] = np.where(df2['Percent'] >= 101, 100, df2['Percent'])
    

    性能对比:

    第 1 部分:原始大小数据框

    旧代码:

    %%timeit
    df.drop(df[df.Percent > 500].index, inplace = True)
    
    # This sets the upper limit on all values at 100
    df['Percent'] = df['Percent'].clip(upper = 100)
    
    1.58 ms ± 56 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    新代码:

    %%timeit
    df2 = df.loc[df['Percent'] <= 500]
    df2['Percent'] = np.where(df2['Percent'] >= 101, 100, df2['Percent'])
    
    784 µs ± 8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    基准测试结果:

    新代码需要 784 µs,而旧代码需要 1.58 ms

    大约快 2 倍

    第 2 部分:大型数据框

    让我们使用原始大小 10000 倍的数据框:

    df9 = pd.concat([df] * 10000, ignore_index=True)
    

    旧代码:

    %%timeit
    df9.drop(df9[df9.Percent > 500].index, inplace = True)
    
    # This sets the upper limit on all values at 100
    df9['Percent'] = df9['Percent'].clip(upper = 100)
    
    3.87 ms ± 175 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    新代码:

    %%timeit
    df2 = df9.loc[df9['Percent'] <= 500]
    df2['Percent'] = np.where(df2['Percent'] >= 101, 100, df2['Percent'])
    
    1.96 ms ± 70.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    基准测试结果:

    新代码需要 1.96 毫秒,而旧代码需要 3.87 毫秒

    速度也快了大约 2 倍

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多