我一直在尝试找出如何根据数据帧的同一元组中的多个其他值来选择某个值。数据看起来像这样(从当前数据帧复制)
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 个值返回到变量中。
最佳答案
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
可以让你输入任何你想要的条件,在这种情况下你可以更简单地做到这一点(正如DSM评论中所指出的)
res = D[(D['DealID'] == "BAC98765") & (D["ServicerId"] == "30220144")]['ServicerPropId']
这给出
In [35]: print res
A 010-002-001
Name: ServicerPropId
In [36]: type(res)
Out[36]: pandas.core.series.Series
关于python - 如何根据 pandas 数据框中的 2 个(或更多)其他值选择某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14665828/