【问题标题】:IF else and for loop in one lineIF else 和 for 在一行中循环
【发布时间】:2018-09-09 11:59:28
【问题描述】:

我需要在单行中应用 if else 条件和 for 循环。我需要一次更新“RL”和“RM”并将其他值更新为“Others”。怎么做??是吗?可能吗??

train['MSZoning']=['RL' if x=='RL' else 'Others' for x in train['MSZoning']]

【问题讨论】:

  • 排长队。
  • 最好避免循环,apply 是引擎盖下的循环。
  • 谢谢。它成功了
  • @Anesh - 当然,这两种解决方案都有效,但更好的是避免循环,避免apply,因为速度很慢。在编辑后的答案中查看我的时间安排。
  • 是的,我看到了。你能解释一下你的代码吗。isin 是做什么的??

标签: python-3.x pandas scikit-learn sklearn-pandas


【解决方案1】:

使用numpy.where:

train['MSZoning'] = np.where(train['MSZoning'] == 'RM', 'RM', 'Others')

如果需要在没有RMRL 的情况下全部更新,请使用isin~ 的反向布尔掩码:

train = pd.DataFrame({'MSZoning':['RL'] *3 + ['qa','RM','as']})
train.loc[~train['MSZoning'].isin(['RM','RL']), 'MSZoning'] =  'Others'

print (train)
  MSZoning
0       RL
1       RL
2       RL
3   Others
4       RM
5   Others

时间安排

train = pd.DataFrame({'MSZoning':['RL'] *3 + ['qa','RM','as']})
#[60000 rows x 1 columns]
train = pd.concat([train] * 10000, ignore_index=True)

In [202]: %timeit train.loc[~train['MSZoning'].isin(['RM','RL']), 'MSZoning'] =  'Others'
5.82 ms ± 447 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [203]: %timeit train['MSZoning'] = train['MSZoning'].apply(lambda x: x if x in ('RM', 'RL') else 'Others')
15 ms ± 584 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

【讨论】:

    【解决方案2】:

    因此,如果您想保留RMRL,同时将其他人标记为Others,您可以使用:

    train['MSZoning'] = train['MSZoning'].apply(lambda x: x if x in ('RM', 'RL') else 'Others')
    

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2019-12-04
      • 2022-01-10
      • 2012-11-13
      • 1970-01-01
      • 2023-04-09
      • 2021-04-18
      • 1970-01-01
      • 2021-09-16
      相关资源
      最近更新 更多