2017-07-16 127 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

謝謝!效果很好 ! –