【问题标题】:Mutate column conditionally有条件地改变列
【发布时间】:2018-11-04 05:28:24
【问题描述】:

我是一名尝试进入 Python 的 R 程序员。在 R 中,当我想有条件地改变一列时,我使用:

col = dplyr::mutate(col, ifelse(condition, if_true(x), if_false(x))

在 Python 中,如何有条件地改变列值?这是我的最小可重现示例:

def act(cntnt):
    def do_thing(cntnt):
        return(cntnt + "has it")
    def do_other_thing(cntnt):
        return(cntnt + "nope")
    has_abc = cntnt.str.contains.contains("abc")
    if has_abc == T:
        cntnt[has_abc].apply(do_thing)
    else:
        cntnt[has_abc].apply(do_other_thing)

【问题讨论】:

  • 请您添加一个关于您的问题和预期结果的小例子吗?另外,我假设if has_abc == T: 实际上是if has_abc == True:

标签: python pandas if-statement conditional


【解决方案1】:

您可以使用条件(及其否定)进行逻辑索引:

has_abc = cntnt.str.contains("abc")
cntnt[ has_abc].apply(do_thing)
cntnt[~has_abc].apply(do_other_thing)

【讨论】:

  • 我不禁认为这太过分了,根本没有给出任何数据
  • @roganjosh 嗯?不知道你的意思。
  • 您的答案与您发布的第一个答案相比发生了很大变化,现在它更有可能是正确的。但是问题中仍然存在if has_abc == T:,因此问题似乎并不完整,如果给出示例数据,您可能会使用np.where 解决问题,而不是分两个阶段的非矢量化方法
  • @roganjosh 我明白你的意思。如果 OP 重新表述他们的问题,那么答案可能会被优化。但先做对,再做快
  • 谢谢!了解如何执行一系列布尔值的逆运算对我有很大帮助。
【解决方案2】:

我认为您正在寻找的是assign,它本质上相当于dplyr 中的mutate。您的条件语句可以使用列表推导式编写,或使用矢量化方法(见下文)。

以数据框为例,我们称之为df

> df
             a
1   0.50212013
2   1.01959213
3  -1.32490344
4  -0.82133375
5   0.23010548
6  -0.64410737
7  -0.46565442
8  -0.08943858
9   0.11489957
10 -0.21628132

R / dplyr:

R 中,您可以使用mutateifelse 来根据条件创建一列(在本例中,当a 列大于0 时,它将是'pos'):

df = dplyr::mutate(df, col = ifelse(df$a > 0, 'pos', 'neg'))

以及由此产生的df

> df
             a col
1   0.50212013 pos
2   1.01959213 pos
3  -1.32490344 neg
4  -0.82133375 neg
5   0.23010548 pos
6  -0.64410737 neg
7  -0.46565442 neg
8  -0.08943858 neg
9   0.11489957 pos
10 -0.21628132 neg

Python / Pandas

pandas 中,将assign 与列表理解一起使用:

df = df.assign(col = ['pos' if a > 0 else 'neg' for a in df['a']])

生成的df

>>> df
          a  col
0  0.502120  pos
1  1.019592  pos
2 -1.324903  neg
3 -0.821334  neg
4  0.230105  pos
5 -0.644107  neg
6 -0.465654  neg
7 -0.089439  neg
8  0.114900  pos
9 -0.216281  neg

您在R 中使用的ifelselist comprehension 替换。

这方面的变化:

您没有使用assign:如果需要,您可以直接在df 上创建一个新列,而无需创建副本:

df['col'] = ['pos' if a > 0 else 'neg' for a in df['a']]

此外,您可以将numpy 的向量化方法之一用于条件语句,例如np.select

import numpy as np
df['col'] = np.select([df['a'] > 0], ['pos'], 'neg')
# or
df = df.assign(col = np.select([df['a'] > 0], ['pos'], 'neg'))

【讨论】:

  • 谢谢!非常彻底的答案。
  • 一流的回答我的家伙!
猜你喜欢
  • 2018-07-02
  • 2018-07-04
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
相关资源
最近更新 更多