gpt4 book ai didi

python - 有条件地改变列

转载 作者:行者123 更新时间:2023-12-04 14:41:25 25 4
gpt4 key购买 nike

我是一名试图进入 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)

最佳答案

我想你要找的是 assign ,它本质上是等价于 mutate 的 Pandas 在 dplyr .您的条件语句可以使用列表推导式编写,或使用矢量化方法(见下文)。

以数据帧为例,我们称之为 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 大于 'pos' 时,它将是 0 ):
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
ifelse您在 R 中使用被 list 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'))

关于python - 有条件地改变列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50518607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com