根据条件替换数据框中的值

时间:2019-01-14 21:00:22

标签: python dataframe conditional-statements where apply

我正在python中使用带有百分比列的Dataframe。我想用“ Likely”替换大于50%的值,而不用“ Not-Likely”替换小于50%的值。

以下是我找到的选项:

df.apply
df.iterrows
df.where

这适用于df.iterrows:

for index, row in df.iterrows():
if row['Chance']>0.50:
    df.loc[index, 'Chance']='Likely'
else:
    df.loc[index, 'Chance']='Not-Likely'

但是,我读到这不是“更新”值的最佳方法。

您将如何使用其他方法执行此操作,您会推荐哪种方法?另外,如果您知道其他方法,请分享!谢谢

1 个答案:

答案 0 :(得分:3)

试一下。

import numpy as np

df['Chance'] = np.where(df['Chance'] > 0.50, 'Likely', 'Not-Likely')

这将使'Not-Likely'等于0.5。

作为一个旁注,据说.itertuples().iterrows()快10倍,zip快100倍。