練習-資料處理(bubbles & sqlalchemy)
試做一個範例 讀取一個CSV檔 算中一個欄位中獨一無二的值並印出結果
如果要在SQL中做這件事就要使用 SELECT JOIN 與 GROUP BY
首先製作一個csv檔
#zoo.csv檔
'''他有這些欄位
動物種類 咬遊客的次數 遊客縫了幾針 以及給遊客的封口費
animal bites stitches hush
'''
import csv
data=[
{'animal':'bear','bites':1,'stitches':35,'hush':300},
{'animal':'marmoset','bites':1,'stitches':2,'hush':250},
{'animal':'bear','bites':2,'stitches':42,'hush':500},
{'animal':'elk','bites':1,'stitches':30,'hush':100},
{'animal':'weasel','bites':4,'stitches':7,'hush':50},
{'animal':'duck','bites':2,'stitches':0,'hush':10},
]
with open('zoo.csv','wt',encoding='utf-8',newline='')as file:
rows=csv.DictWriter(file,['animal', 'bites', 'stitches', 'hush'])
rows.writeheader() #寫入標題
rows.writerows(data)
'以上是製作zoo.csv'
------------------animal,bites,stitches,hush
bear,1,35,300
marmoset,1,2,250
bear,2,42,500
elk,1,30,100
weasel,4,7,50
duck,2,0,10
------------------------------------
'計算哪一種動物花掉最多錢 彙整動物所花費的總封口費'
cos={}
with open('zoo.csv','rt')as file:
rows=csv.reader(file)
next(rows)#略過標題
for i in rows:
# print(i[0],i[-1])
cos[i[0]]=cos.get(i[0],0)+int(i[-1])
for animal, hush in cos.items():
print(f'{animal:>8}{hush:>8}')
---------------------
bear 800
marmoset 250
elk 100
weasel 50
duck 10
----------------------------------------
import bubbles
#這個套件用來處理資料
#注意 sqlalchemy 使用的是1.3.20版本 ,1.4以上都會有Binary屬性錯誤
p=bubbles.Pipeline()
#建立一個Pipline物件p,他是bubbles套件中用來串聯資料處理步驟的容器
p.source(bubbles.data_object('csv_source','zoo.csv',infer_fields=True))
#bubbles.data_object()如果是csv檔通常只需要source_type source_name infer_fields參數即可
#設定資料來源
#使用bubbles.data_object()函式來建立一個資料物件,並指定zoo.csv為資料來源
#使用infer_fields=True 參數讓套件自動推斷資料欄位
p.aggregate('animal','hush')
#在Pipline中天家具和步驟,使用aggregate()指定聚合的依據欄位
#也就是aggregate()根據指定的欄位對資料進行聚合運算
#這邊傳遞了animal和hush作為參數,將會對這兩個欄位進行聚合運算,通常會是計算他們的加總或是平均值等
#從zoo.csv讀取資料然後根據,animal和hush進行聚合
p.pretty_print()
#輸出Pipline內容,讓她已一讀的方式顯示出來
--------------------
2023-07-22 16:30:54,294 DEBUG calling aggregate(rows)
2023-07-22 16:30:54,294 INFO called aggregate(rows)
2023-07-22 16:30:54,294 DEBUG calling pretty_print(records)
+--------+--------+------------+
|animal |hush_sum|record_count|
+--------+--------+------------+
|duck | 10| 1|
|weasel | 50| 1|
|bear | 800| 2|
|marmoset| 250| 1|
|elk | 100| 1|
+--------+--------+------------+
2023-07-22 16:30:54,296 INFO called pretty_print(records)
標籤: 練習

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁