我有以下几行代码:
import pandas as pd
df1 = pd.DataFrame({'Counterparty':['Bank','Client','GSE','PSE'],
'Maturity':[2, 3, 2, 2],
'Amount':[50, 55, 65, 55],
'Match':[0,0,0,0]})
CounterpartyList=['Bank','Client']
MaturityList=[2,3]
df1.loc[(df1['Counterparty'].isin (CounterpartyList))& (df1['Maturity'].isin (MaturityList)),'Match']=420
如果两个列表(CounterpartyList 或 MaturityList)中的任何一个有一个“#”,我希望代码的行为如下:
import pandas as pd
df1 = pd.DataFrame({'Counterparty':['Bank','Client','GSE','PSE'],
'Maturity':[2, 3, 2, 2],
'Amount':[50, 55, 65, 55],
'Match':[0,0,0,0]})
CounterpartyList=['Bank','Client']
MaturityList=['#']
df1.loc[(df1['Counterparty'].isin(CounterpartyList)) ,'Match']=420
即,当 MaturityList 或 CounterpartyList 包含 # 时,我会忽略匹配条件。
对于最有效的方法有什么想法吗?我有很多条件,所以想避免大的 CASE 条件
请您参考如下方法:
您可能想为每个列表创建一个 bool 掩码,然后相交
>> bm1 = ('#' in CounterpartyList) | df1['Counterparty'].isin(CounterpartyList)
>> bm2 = ('#' in MaturityList) | df1['Maturity'].isin(MaturityList)
>> df1.loc[bm1 & bm2, 'Match'] = 420
>> df1
Amount Counterparty Match Maturity
0 50 Bank 420 2
1 55 Client 420 3
2 65 GSE 0 2
3 55 PSE 0 2
