Chr*_*llo 3 python conditional if-statement pandas
我是一名试图进入 Python 的 R 程序员。在 R 中,当我想有条件地改变一列时,我使用:
col = dplyr::mutate(col, ifelse(condition, if_true(x), if_false(x))
Run Code Online (Sandbox Code Playgroud)
在 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)
Run Code Online (Sandbox Code Playgroud)
我认为你正在寻找的是assign,它本质上是相当于mutatein的熊猫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
Run Code Online (Sandbox Code Playgroud)
R/ dplyr:在 中R,您可以使用mutatewithifelse根据条件创建列(在此示例中,'pos'当列 a 大于 时0):
df = dplyr::mutate(df, col = ifelse(df$a > 0, 'pos', 'neg'))
Run Code Online (Sandbox Code Playgroud)
结果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
Run Code Online (Sandbox Code Playgroud)
Python / Pandas在 中pandas,assign与列表理解一起使用:
df = df.assign(col = ['pos' if a > 0 else 'neg' for a in df['a']])
Run Code Online (Sandbox Code Playgroud)
结果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
Run Code Online (Sandbox Code Playgroud)
在ifelse您使用的R是通过更换列表理解。
你不具备使用assign:您可以直接在创建新列df不创建副本情况下:
df['col'] = ['pos' if a > 0 else 'neg' for a in df['a']]
Run Code Online (Sandbox Code Playgroud)
此外,您可以将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'))
Run Code Online (Sandbox Code Playgroud)