2017-07-16 133 views
2

我有下面的代码行:灵活选择在大熊猫据帧

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当它们含有#的状态。

任何想法的最有效的方法来做到这一点?我有相当多的条件,所以要避免

+0

大CASE条件如果没有'CounterpartyList'和'MaturityList'包含'#'? – tarashypka

+0

然后'匹配'将填充所有行 –

回答

2

您可能希望创建一个bollean面具每个列表,然后相交他们

>> 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 
+0

谢谢!效果很好 ! –