由于许多潜在的Pandas用户对SQL有一定的了解,因此本文章旨在提供一些如何使用Pandas执行各种SQL操作的示例。
import pandas as pd url = 'tips.csv' tips=pd.read_csv(url) print (tips.head())
文件:tips.csv –
total_bill,tip,sex,smoker,day,time,size 0,16.99,1.01,Female,No,Sun,Dinner,2 1,10.34,1.66,Male,No,Sun,Dinner,3 2,21.01,3.50,Male,No,Sun,Dinner,3 3,23.68,3.31,Male,No,Sun,Dinner,2 4,24.59,3.61,Female,No,Sun,Dinner,4
执行上面示例代码,得到以下结果 –
total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4
选择(Select)
在SQL中,选择是使用逗号分隔的列列表(或选择所有列)来完成的,例如 –
SELECT total_bill, tip, smoker, time FROM tips LIMIT 5;
在Pandas中,列的选择是通过传递列名到DataFrame –
tips[['total_bill', 'tip', 'smoker', 'time']].he