Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在其他列上迭代向量化的if/else语句?_Python_Pandas_Dataframe - Fatal编程技术网

Python 如何在其他列上迭代向量化的if/else语句?

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。其中语句:

我需要检查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。其中
语句:

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