![](/img/trans.png)
[英]Python pandas equivalent to R's group_by, mutate, and ifelse
[英]Equivalent of R's ifelse in Python
我是 Python 的新手,如果这是一个基本问题,请原谅我。 我正在将我的 R 代码转换为 Python。 我尝试使用来自其他两个变量的数据创建新变量。 在 R 我会做以下事情:
df$new_col <- ifelse(is.na(df$col1) & is.na(df$col2), 99,
ifelse(is.na(df$col1) & !is.na(df$col2), df$col2,
ifelse(is.na(df$col2) & !is.na(df$col1), df$col1,
ifelse(df$col2 > df$col1, df$col1,
ifelse(df$col2 < df$col1, df$col2,
ifelse(df$col1==df$col2, df$col2, "Error in coding"))))))
我在类似问题的答案中看到了下面的一些代码,当我只有一个条件时有效,但当它更复杂时我无法让它工作。
df['new_col'] = np.where(df['col1'].isnull() and df['col2'].isnull(), x, y)
任何帮助将不胜感激。
您可以将列表理解与 function 一起使用。
a = [np.nan,1,2,3]
b = [np.nan,-1,5,np.nan]
def build_list(a_i, b_i):
if np.isnan(a_i) and np.isnan(b_i):
return 99
elif np.isnan(a_i) and ~np.isnan(b_i):
return b_i
elif ~np.isnan(a_i) and np.isnan(b_i):
return a_i
elif a_i > b_i:
return a_i
elif a_i < b_i:
return b_i
else:
return "Error in coding"
[build_list(item[0], item[1]) for item in zip(a, b)]
[99, 1.0, 5.0, 3.0]
这是您将其合并到 pandas 中的方法(assign 正在执行 dplyr 的 mutate 工作)
import pandas as pd
example_df = pd.DataFrame({'a':a, 'b':b})
example_df.assign(c = lambda df: [build_list(item[0], item[1]) for item in zip(df['a'], df['b'])] )
由此产生的 dataframe -
a b c
0 NaN NaN 99.0
1 1.0 -1.0 1.0
2 2.0 5.0 5.0
3 3.0 NaN 3.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.