データサイエンス100本ノックで勉強(5)

前回に引き続きSQLPythonでデータサイエンス100本ノック進めていきます。

github.com

S-006: レシート明細テーブル(receipt)から売上日(sales_ymd)、顧客ID(customer_id)、商品コード(product_cd)、売上数量(quantity)、売上金額(amount)の順に列を指定し、以下の条件を満たすデータを抽出せよ。
顧客ID(customer_id)が"CS018205000001" 売上金額(amount)が1,000以上または売上数量(quantity)が5以上

まず自分で以下のSQLを書いてみたのですが、

%%sql
select sales_ymd, customer_id, product_cd, quantity, amount from receipt
where customer_id = 'CS018205000001'
and amount >= 1000 or quantity >= 5;

これだとcustomer_idがCS018205000001以外のレコードも含まれてしまっていました。
f:id:JunpeiNakasone:20220126064319p:plain 正しくは以下のSQLのようにor条件が入るところに()をつける必要がありました。

%%sql
select sales_ymd as sales_date, customer_id, product_cd, quantity, amount from receipt
where customer_id = 'CS018205000001'
and ( amount >= 1000 or quantity >= 5);

これでcustomer_idがCS018205000001を抽出した上でamountとquantityに対してWhere条件を指定できました。

f:id:JunpeiNakasone:20220126064647p:plain

Pythonでは以下のようになります。

df_receipt[['sales_ymd','customer_id','product_cd','quantity','amount']].\
    query('customer_id=="CS018205000001" &(amount >= 1000 | quantity >= 5)')

f:id:JunpeiNakasone:20220126064956p:plain

「|」はorに書き換えても同様に動きました。

f:id:JunpeiNakasone:20220126065040p:plain