如何在其他列上迭代vectorized if / else语句?

时间:2018-05-07 00:23:14

标签: python pandas dataframe

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)

我需要检查ID2列并写入ID,除非它已经有ID。

输出

ID  ID2 LT
1   3   1
3   4   0
4   5   0
5   6   0
6   7   0
7   2   2

谢谢!

1 个答案:

答案 0 :(得分:0)

选项1

您可以嵌套numpy.where语句:

org['LT'] = np.where(org['ID'].isin(ltlist_set), 1,
                     np.where(org['ID2'].isin(ltlist_set), 2, 0))

选项2

或者,您可以按顺序使用pd.DataFrame.loc

org['LT'] = 0  # default value
org.loc[org['ID2'].isin(ltlist_set), 'LT'] = 2
org.loc[org['ID'].isin(ltlist_set), 'LT'] = 1

选项3

第三种选择是使用numpy.select

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