【问题标题】:Translating R mutate conditional across two columns to Python将跨两列的 R mutate 条件转换为 Python
【发布时间】: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


【解决方案1】:

我猜“字面”翻译应该是这样的:

df = df[[col_1,...,col_n]]
df['new_col'] = np.where(df['col_1'].isnull(), 
                         np.nan, 
                         2)
df['new_col'] = np.where(df['col_2'].isnull(), 
                         df['new_col'], 
                         np.where(df['col_3'] == 1, 
                                  df['new_col']+1, 
                                  df['new_col']-1))

【讨论】:

  • 哇,它做到了!!!我想我也可以将这种方法用于其余的应用方法。非常感谢您的帮助。
  • 嗨@donutpancake 如果这个答案已经解决了你的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。谢谢!
  • 嗨@LeonardoViotti 完成!再次感谢您的帮助!
【解决方案2】:

您还可以使用datar 顺利地将您的 R 代码翻译成 python:

>>> from datar.all import NA, f, tibble, select, mutate, if_else, is_na
>>> 
>>> df = tibble(
...     col_1 = [1, NA, 2, 3],
...     col_2 = [4, 5, NA, 7],
...     col_3 = [8, 9, 10, 1],
...     unk_col = list('abcd')
... )
>>> 
>>> df >> select(f.col_1, f.col_2, f.col_3) >> mutate(
...     new_col_ = if_else(is_na(f.col_1), NA, 2),
...     new_col = if_else(
...         is_na(f.col_2), 
...         f.new_col, 
...         if_else(f.col_3 == 1, f.new_col+1, f.new_col-1)
...     )
... )
      col_1     col_2   col_3   new_col
  <float64> <float64> <int64> <float64>
0       1.0       4.0       8       1.0
1       NaN       5.0       9       NaN
2       2.0       NaN      10       2.0
3       3.0       7.0       1       3.0

我是datar 包的作者。如果您有任何问题,请随时提交问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多