首页 > 解决方案 > 如何使用可以更改的列表在多列上迭代矢量化 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

谢谢!

标签: pythonpandas

解决方案


由于您将0其用作默认值,因此您可以将其作为orwith 传递给数据框。

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]:
    ...

推荐阅读