2013-02-02 42 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

相关问题