Python 如何使用可以更改的列表在多个列上迭代向量化的if/else语句?
ltlist中的数字指的是可以更改的ID号,如果本例中ltlist中的元素不是常量,是否可以通过ltlist中项目的多列进行读写。希望使用循环而不是矢量化的if/else,但无法使其工作Python 如何使用可以更改的列表在多个列上迭代向量化的if/else语句?,python,pandas,Python,Pandas,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
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
作为默认值,因此可以将其作为或
传递到数据帧
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
这将始终保留在ltlist
中具有值的最右边列的值。如果希望保留最左边有值的列,可以反向迭代这些列
for col in org.columns.drop('LT')[::-1]:
...
谢谢你,James,当我运行控制台时,你的代码运行得很好。当我用实际数据将其应用于示例时,我得到的“ltset”没有定义。