首页 > 解决方案 > 行和的 Python 等效项

问题描述

在此处输入图像描述

样本数据

我有一个 R 代码,我想将它转换为类似的 python 代码。这是 R 代码片段:

data$total <- ifelse(data$dpd_gt_30 == 1 , rowSums(data[0:2]),
                 ifelse(data$dpd_gt_30 == 3 , rowSums(data[2:4]),1000))

我在做什么 :

data['total']=data.iloc[:, 0:2].sum(axis=1).where(data['dpd_gt_30'] == 1,1000)

如何为此添加多个(如果需要,超过 2 个)条件?

编辑:

我按照说明做了这个:

conds = [
    df['dpd_gt_30'] == 1, 
    df['dpd_gt_30'] == 3,
    df['dpd_gt_30'] not in [1,3]
]

choices = [
    df.iloc[:,0:2].sum(axis=1),
    df.iloc[:,2:4].sum(axis=1),
    1000
    ]

df['Total'] = np.select(conds, choices)

现在我该如何处理不属于条件的值?(值既不是 1 也不是 3 的情况)

标签: pythonpandasdataframeif-statement

解决方案


使用np.where

data['total'] = np.where(data['dpd_gt_30']==1, data.iloc[:,:2].sum(axis=1),
                         data.iloc[:,2:].sum(axis=1)
                        )

推荐阅读