python - 如何使用可以更改的列表在多列上迭代矢量化 if/else 语句?
问题描述
ltlist 中的数字是指可以更改的 ID 号,是否可以通过多个列来读取 ltlist 中的项目,假设此示例中 ltlist 中的元素不是恒定的。希望也使用循环而不是矢量化 if/else 但无法使其正常工作。
import pandas as pd, numpy as np
ltlist = [1, 2]
org = {'ID': [1, 3, 4, 5, 6, 7], 'ID2': [3, 4, 5, 6, 7, 2]}
ltlist_set = set(ltlist)
org['LT'] = np.where(org['ID'].isin(ltlist_set), org['ID'], 0)
I'll need to check the ID2 column and write the ID in, unless it already has an ID.
输出
ID ID2 LT
1 3 1
3 4 0
4 5 0
5 6 0
6 7 0
7 2 2
谢谢!
解决方案
由于您将0
其用作默认值,因此您可以将其作为or
with 传递给数据框。
import pandas as pd
import numpy as np
ltset = set([1, 2])
org = pd.DataFrame({'ID': [1, 3, 4, 5, 6, 7], 'ID2': [3, 4, 5, 6, 7, 2]})
org['LT'] = 0
for col in org.columns.drop('LT'):
org['LT'] = np.where(org[col].isin(ltset), org[col], org['LT']|0)
org
# returns:
ID ID2 LT
0 1 3 1
1 3 4 0
2 4 5 0
3 5 6 0
4 6 7 0
5 7 2 2
这将始终保留具有 in 值的最右侧列的值ltlist
。如果要保留具有值的最左侧列,则可以反向遍历列。
for col in org.columns.drop('LT')[::-1]:
...
推荐阅读
- powerbi - 切片器同时跨表管理多个列
- c - 如何运行随机语句
- javascript - 使用 Chrome 扩展覆盖 Element.prototype.attachShadow
- javascript - React useEffect 导致:无法对未安装的组件执行 React 状态更新
- c# - 每次我从矩形数组中删除一个项目时都会出现异常
- browser - 浏览器扩展可以访问我的脚本中的本地范围变量吗?
- .net - 构造函数中的这个参数如何直接在 FSharp 中的成员方法中使用?
- ruby - 有没有办法为 Chef 资源的 name 属性指定默认值?
- command - 将文件从 1 移动到不同的文件夹
- vba - MSAccess 2010 VBA 打开只读数据库