根据Pandas中的多个条件选择列

时间:2019-03-08 06:06:25

标签: python pandas dataframe

如何将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

1 个答案:

答案 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"]]