繁体   English   中英

Pandas Dataframe 以给定的间隔更改列值

[英]Pandas Dataframe change column values with given interval

我正在尝试根据间隔转换我的列值,例如,

if(x<5)
  x=2
else if(x>=5 %% x<10)
  x=3

并尝试使用单行代码在 python 中进行操作。 使用蒙版和剪切方法,但我做不到。 这是我的审判,

dataset['CURRENT_RATIO' ] = dataset['CURRENT_RATIO'].mask((dataset['CURRENT_RATIO'] < 0.02, -7.0) | (dataset['CURRENT_RATIO'] > =0.02 & dataset['CURRENT_RATIO'] < 0.37),-5))

if x<0.02 then -7 else if x>=0.02 and x<0.37 then -5...

  inptut output
    0.015  -7
    0.02   -5
    0.37   -3
    0.75   1

TL;博士

列表理解将执行以下操作:

dataset.CURRENT_RATIO = [-7 if i<.02 else -5 if i<.37 else -3 if i<.75 else 1 for i in dataset.CURRENT_RATIO]

使用 1,000,000 行的随机数据集对其进行计时,得到以下结果:

334 ms ± 5.89 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

多列

如果您要对具有不同阈值和更新值的多个列执行此操作,我将执行以下操作:

df = pd.DataFrame({'RATIO1': np.random.rand(10000000),
                   'RATIO2': np.random.rand(10000000)})

update_per_col = {'RATIO1': [(.02, -7), (.37, -5), (.75, -3), 1],
                  'RATIO2': [(.12, 5), (.47, 6), (.85, 7), 8]}
cols_to_be_updated = ['RATIO1', 'RATIO1']

for col in cols_to_be_updated:
    df[col] = [update_per_col[col][0][1] if i<update_per_col[col][0][0] else 
               update_per_col[col][1][1] if i<update_per_col[col][1][0] else 
               update_per_col[col][2][1] if i<update_per_col[col][2][0] else update_per_col[col][3]
               for i in df[col]]

当我们用 10,000,000 行和两列来计时 for 循环时,我们得到:

9.37 s ± 147 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

为了解决 Joe Ferndz 的评论,让我们尝试加快速度。 我想出了两种方法: apply()lambda 使用apply()我们运行以下代码(只有 for 循环是定时的):

def update_ratio(x, updates):
    if x < updates[0][0]:
        return updates[0][1]
    elif x < updates[1][0]:
        return updates[1][1]
    elif x < updates[2][0]:
        return updates[2][1]
    else:
        return updates[3]

for col in cols_to_be_updated:
    df[col] = df[col].apply(update_ratio, updates=update_per_col[col])

这给了我们:

11.8 s ± 285 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

最后lambda给出:

for col in cols_to_be_updated:
    df[col] = df[col].apply(lambda x: update_per_col[col][0][1] if x<update_per_col[col][0][0] else 
              update_per_col[col][1][1] if x<update_per_col[col][1][0] else 
              update_per_col[col][2][1] if x<update_per_col[col][2][0] else 
              update_per_col[col][3])

8.91 s ± 171 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

这意味着 lambda 是最快的方法,但列表理解并不遥远。

利用

dataset['CURRENT_RATIO'][dataset['CURRENT_RATIO']<10]=3
dataset['CURRENT_RATIO'][dataset['CURRENT_RATIO']<5]=2

第一行您将所有小于 10 的值设为 3,然后将所有小于 5 的值设为 2 它使 5 到 10 之间的所有值保持为 3

编写自己的lambda函数并使用pandas.apply()会很聪明

def my_lambda(x):
    if(x<5):
        x=2
    elif(x<10):
        x=3
    return x

dataset['CURRENT_RATIO' ] = dataset['CURRENT_RATIO'].apply(my_lambda)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM