2013-02-02 80 views
2

我一直在試圖找出如何根據數據幀的同一元組中的多個其他值選擇某個值。數據看起來像這樣(從當前數據幀複製)如何根據熊貓數據框中的2個(或更多)其他值來選擇某個值

DealID  PropId LoanId ServicerId ServicerPropId 
0 BAC98765  15 000015 30220144  010-002-001 
1 BAC98765  16 000016 30220092  010-003-001 
2 BAC98765  45 000045 30220155  010-045-001 
3 BAC98765  48 000048 30220157  010-048-001 

在SQL方面我想完成的是:

Select ServicerPropId from dataframe 
where DealID = 'BAC98765' and ServicerId = '30220144' 

我已經嘗試了幾種不同的方式切片數據,但似乎無法弄清楚如何獲得多個選擇標準,並只將1個值返回到變量中。

回答

2
columns = ['DealID', 'PropId', 'LoanId', 'ServicerId', 'ServicerPropId'] 

d = [('A', [ 'BAC98765', '15', '000015', '30220144', '010-002-001']), 
    ('B', [ 'BAC98765', '16', '000016', '30220092', '010-003-001']), 
    ('C', [ 'BAC98765', '45', '000045', '30220155', '010-045-001']), 
    ('D', [ 'BAC98765', '48', '000048', '30220157', '010-048-001']),] 

D = pandas.DataFrame.from_items(d, orient='index', columns=columns) 

criterion1 = D['DealID'].map(lambda x: x == 'BAC98765') 
criterion2 = D['ServicerId'].map(lambda x: x == '30220144') 

res = D[criterion1 & criterion2]['ServicerPropId'] 

使用map可以讓你把任何你想要的狀態,在這種情況下,你可以做到這一點更簡單地說其中給出

res = D[(D['DealID'] == "BAC98765") & (D["ServicerId"] == "30220144")]['ServicerPropId'] 

(如在由DSM評論中指出)

In [35]: print res 
A 010-002-001 
Name: ServicerPropId 

In [36]: type(res) 
Out[36]: pandas.core.series.Series 

(doc)

+5

我不認爲地圖是必要的; D [(D ['DealID'] ==「BAC98765」)&(D [「ServicerId」] ==「30220144」)]''應該工作。 – DSM

+0

工作得很好 - 在我的特殊情況下,不需要映射,但是您提供的最後一行代碼正是我所需要的。謝謝。 –

+0

就像DSM的最後一個非地圖解決方案一樣,爲我工作 – dartdog

相關問題