我有一个如下所示的熊猫数据框:
x y z
1 2 3
na 1 4
na na 5
现在我想添加另一列 a,其值取决于 x、y 和 z。如果 x 可用,则 a 将为“是”。如果是na,那么它将检查y。如果 y 可用,则 a 将为“否”,否则 a 将与 z 相同(如果可用,否则将为 0)。我在 R 中有以下功能:
cur_sta <- function(data){
sta <- ifelse(!is.na(data$x),"yes",
ifelse(!is.na(data$y),"no",
ifelse(!is.na(data$z),data$z,0)))
}
我怎样才能在python中实现同样的目标?
编辑:
我尝试了以下方法:
conditions = [
(not pd.isnull(data["x"].item())),
(not pd.isnull(data["y"].item())),
(not pd.isnull(data["z"].item()))]
choices = ['yes', 'no', data["z"]]
data['col_sta'] = np.select(conditions, choices, default='0')
但我收到以下错误:
ValueError: can only convert an array of size 1 to a Python scalar
我怎样才能解决这个问题?