|
| 1 | +# PYTHON TIPS ---- |
| 2 | +# TIP 002 | Siuba: Dplyr for Python ---- |
| 3 | +# |
| 4 | +# 👉 For Weekly Python-Tips, Sign Up Here: |
| 5 | +# https://mailchi.mp/business-science/python_tips_newsletter |
| 6 | + |
| 7 | +# LIBRARIES ---- |
| 8 | +import numpy as np |
| 9 | +import pandas as pd |
| 10 | + |
| 11 | +from siuba import _ |
| 12 | +from siuba.dply.verbs import group_by, mutate, select, summarize, ungroup |
| 13 | + |
| 14 | +# DATASET ---- |
| 15 | + |
| 16 | +mpg_df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv") |
| 17 | +mpg_df |
| 18 | + |
| 19 | +# 1.0 GROUP BY + SUMMARIZE |
| 20 | +# Goal: Mean and Standard Deviation of weight by engine size |
| 21 | + |
| 22 | +weight_by_cyl_df = mpg_df >> \ |
| 23 | + group_by("cylinders") >> \ |
| 24 | + summarize( |
| 25 | + mean_weight = np.mean(_.weight), |
| 26 | + sd_weight = np.std(_.weight) |
| 27 | + ) |
| 28 | + |
| 29 | +weight_by_cyl_df |
| 30 | + |
| 31 | +# 2.0 GROUP BY + MUTATE |
| 32 | +# Goal: De-mean the mpg by average of each cylinder |
| 33 | + |
| 34 | +mpg_demeaned_by_cyl_df = mpg_df >> \ |
| 35 | + select('name', 'cylinders', 'mpg') >> \ |
| 36 | + group_by("cylinders") >> \ |
| 37 | + mutate( |
| 38 | + mean_mpg = np.mean(_.mpg) |
| 39 | + ) >> \ |
| 40 | + ungroup() >> \ |
| 41 | + mutate( |
| 42 | + mpg_demeaned_by_cyl = _.mpg - _.mean_mpg |
| 43 | + ) |
| 44 | + |
| 45 | +mpg_demeaned_by_cyl_df |
| 46 | + |
| 47 | +# 3.0 PANDAS |
| 48 | +mpg_demeaned_by_cyl_df[['name', 'cylinders', 'mpg_demeaned_by_cyl']] \ |
| 49 | + .sort_values('mpg_demeaned_by_cyl', ascending = False) \ |
| 50 | + .style \ |
| 51 | + .background_gradient() |
| 52 | + |
| 53 | +# LEARNING PANDAS ---- |
| 54 | +# - Siuba is great for when you are coming from R to Python (like me) |
| 55 | +# - Teams use Pandas: 99% of data wranlging code is written with Pandas |
| 56 | +# - Better Learn Pandas if you want to be part of the Team |
| 57 | + |
| 58 | +# I TEACH PANDAS (FROM AN R-USERS PERSPECTIVE)! |
| 59 | +# Python for Data Science Automation Course (Contains 5 hours of Pandas) |
| 60 | +# https://university.business-science.io/p/python-for-data-science-automation-ds4b-101p |
0 commit comments