我是 Python 的新手,我正在尝试进行分析。但在此之前,我想重新编码一些变量。我想知道这段 R 代码在 Python 中是否有等效代码。
df$col1 <- ifelse(df$col1 == "yes", 1, 0)
这里 df
是一个 pandas.DataFrame
而 col1
是它的列之一。
最佳答案
一个可能的选择——在语法方面可能与 R 的 ifelse
最相似——是使用 where
来自 numpy
import numpy as np
df['col1'] = np.where(df['col1'] == "Yes", 1, 0)
关于python - 在 Python 中重新编码类似于 R ifelse 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62772341/