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

Replacing Values in Dataframe Based on Condition

我在 python 中使用一个包含百分比列的数据框。我想用 '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'

但是,我了解到这不是 'updating' 值的最佳方式。

如果使用其他方法,您将如何做到这一点?您会推荐哪一种?另外,如果你知道任何其他方法,请分享!谢谢

试一试。

import numpy as np

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

然而,这将使任何东西 = .50 为 'Not-Likely'

正如旁注,据说 .itertuples().iterrows() 快大约 10 倍,zip 大约快 100 倍。