如何将SQL语句转换为Pandas:
select PolicyNumber,
Coverage
from ClaimsData
where AccidentState = 'AZ' and Coverage = 'Liability'
我知道如何为单个条件(AccidentState ='AZ')选择列,但是如何添加另一个条件?
ClaimsData[["PolicyNumber","Coverage","AccidentState"]] [ClaimsData["AccidentState"]=="AZ"] # and here I need to add another condition
答案 0 :(得分:4)
您可以按条件&
链接条件按位AND
并按条件DataFrame.loc
按条件boolean indexing
按行DataFrame.query
和按list
按列名按列进行过滤:
mask = (ClaimsData["AccidentState"]=="AZ") & (ClaimsData["Coverage"]=="Liability")
df = ClaimsData.loc[mask, ["PolicyNumber","Coverage"]]
就像@Sandeep Kadapa指出的那样,{{3}}可以替代:
q = "AccidentState == 'AZ' & Coverage == 'Liability'"
df = ClaimsData.query(q)[["PolicyNumber","Coverage"]]