python - 在 Pandas 中跨多个列的 if 语句
问题描述
这是我拥有的数据:
| total | big | med | small| big_perc | med_perc | sml_perc |
|:-----:|:-----:|:-----:|:----:|:--------:|:--------:|:--------:|
| 5 | 4 | 0 | 1 | 0.8 | 0.0 | 0.2 |
| 6 | 0 | 3 | 3 | 0.0 | 0.5 | 0.5 |
| 5 | 2 | 3 | 0 | 0.4 | 0.6 | 0.0 |
这就是我想要创建的:
| total | big | med | sml | big_perc | med_perc | sml_perc | condition | size |
|:-----:|:-----:|:-----:|:----:|:--------:|:--------:|:--------:|:--------: |:--------:
| 5 | 4 | 0 | 1 | 0.8 | 0.0 | 0.2 | YES | big |
| 6 | 0 | 3 | 3 | 0.0 | 0.5 | 0.5 | NO | |
| 5 | 2 | 3 | 0 | 0.4 | 0.6 | 0.0 | YES | med |
对于条件列 id,如果 big_perc、med_perc 或 sml_perc 大于 0.6 则表示“是”,如果不满足该条件则为空白。
对于大小列 id 来说,无论哪一列大于 0.6,否则也为空白
这是我尝试过的:
for (df['condition'] in len(df):
if df['big_perc'] >= 0.60:
df['condition'] = 'YES'
elif df['med_perc'] >= 0.60:
df['condition'] = 'YES'
elif df['sml_perc'] >= 0.60:
df['condition'] = 'YES'
else:
df['condition'] = ''
我为 size 列尝试了相同的 for/if 语句
解决方案
对于condition
列,np.where就足够了,因为它只是一个条件;但是对于该size
列,由于它具有多个条件,因此 np.select应该适合:
df["condition"] = np.where(df.filter(like="perc").ge(0.6).any(axis=1), "YES", "NO")
cond1 = df.filter(like="perc").gt(0.6).any(axis=1)
cond2 = df.filter(like="perc").ge(0.6).any(axis=1)
cond3 = df.filter(like="perc").lt(0.6).all(axis=1)
condlist = [cond1, cond2, cond3]
choicelist = ["big", "med", ""]
df["size"] = np.select(condlist, choicelist)
total big med small big_perc med_perc sml_perc condition size
0 5 4 0 1 0.8 0.0 0.2 YES big
1 6 0 3 3 0.0 0.5 0.5 NO
2 5 2 3 0 0.4 0.6 0.0 YES med
推荐阅读
- recursion - 如何在 SML 中使用 map 函数来实现此代码?
- python - 确定最大 UDP 数据报大小的跨平台方法
- python - 根据列字典值过滤数据框
- wso2 - WSO2IS 5.10.0 - 通过 deployment.toml 配置 RootPartition
- tensorflow - 为什么从量化感知训练模型派生的 TFLite 模型与具有相同权重的正常模型不同?
- r - 奇怪的平淡奥特曼情节
- python - scipy中exp1的日志
- data-analysis - 从存储的文本字符串中识别可能的条形码符号的方法?
- python - 如何用例如使用字典的代码替换大型 if-elif 语句?
- reactjs - react docker项目的权限错误:EACCES:权限被拒绝,mkdir'/app/node_modules/.cache'