Python 如何在其他列上迭代向量化的if/else语句?
我需要检查ID2列并写入ID,除非它已经有ID 输出Python 如何在其他列上迭代向量化的if/else语句?,python,pandas,dataframe,Python,Pandas,Dataframe,我需要检查ID2列并写入ID,除非它已经有ID 输出 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) 谢谢 选项1 您可以嵌套numpy。其中语句:
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)
谢谢 选项1 您可以嵌套
numpy。其中语句:
ID ID2 LT
1 3 1
3 4 0
4 5 0
5 6 0
6 7 0
7 2 2
选项2
或者,您可以按顺序使用pd.DataFrame.loc
:
org['LT'] = np.where(org['ID'].isin(ltlist_set), 1,
np.where(org['ID2'].isin(ltlist_set), 2, 0))
选项3
第三个选项是使用numpy。选择:
org['LT'] = 0 # default value
org.loc[org['ID2'].isin(ltlist_set), 'LT'] = 2
org.loc[org['ID'].isin(ltlist_set), 'LT'] = 1
conditions = [org['ID'].isin(ltlist_set), org['ID2'].isin(ltlist_set)]
values = [1, 2]
org['LT'] = np.select(conditions, values, 0) # 0 is default value