python - 行和的 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 的情况)
解决方案
使用np.where
:
data['total'] = np.where(data['dpd_gt_30']==1, data.iloc[:,:2].sum(axis=1),
data.iloc[:,2:].sum(axis=1)
)
推荐阅读
- r - hms 函数踢出 NA
- google-maps - Phonegap/Cordova 地理定位提醒特定位置附近有什么
- c# - 除非存在框架 3.5,否则程序集无法通过 COM 互操作加载?
- python - 靠近对象时如何抵消x和y坐标的缩放
- javascript - 有谁知道为什么会出现这个数学和本地存储问题?
- angular - 如何访问由组件工厂解析器动态创建的组件内的实例变量
- python - 查询字典时返回不同的值
- c# - 以编程方式添加的 MSMQ 队列不同于手动创建
- heroku - 如何将 docker 镜像推送到从 Docker Hub 拉取的 Heroku
- java - 列表
到地图 显示每分钟的日期元素数量