【发布时间】:2021-07-30 02:34:02
【问题描述】:
我正在将 R 中的某些内容翻译成 Python,但我不明白如何在两列中实现与 Python 中可比的内容的条件变异函数。
df <- df %>%
select(col_1,…,col_n) %>%
mutate(new_col = ifelse(is.na(col_1), NA, 2),
new_col = ifelse(is.na(col_2), new_col, ifelse(col_3 == 1, new_col+1, new_col-1))).
到目前为止,我有以下 col_1 是字符串,col_2 是字符串,col_3 是浮点数:
df = df[[col_1,...,col_n]]
df[new_col] = df[col_1].apply(lambda x: np.nan if x is np.nan else 2)
并且无法弄清楚如何进行下一个突变。我尝试了以下方法:
1. df[new_col] = df.apply[col_2](lambda x: x if x is ' ' else df[col_3].apply(lambda x: x+1 if x == 1 else x-1)
# This timesout the kernel
2. df[new_col] = df.apply(lambda x: x if x[col_2] == ' ' else x+1 if x[col_3] == 1 else x-1 if x[col_3] != else x)
# This results in an error of unsuporrted operand type(s) for -: 'str' and 'int'
# I also don't think the 'else x' at the end is the correct way to get the same result
有没有办法通过比嵌套应用更便宜的计算方法(如果这甚至是一种正确的攻击方法)或手动提取必要信息的方法来做到这一点?
【问题讨论】:
-
don't compare to "" use numpy,不用apply 这只是一堆ifelse,请创建一个reprex
-
请创建具有预期输出的示例数据框
标签: python r pandas dplyr translate