# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Window functions
#
# General Elections were held in the UK in 2015 and 2017. Every citizen votes in a constituency. The candidate who gains the most votes becomes MP for that constituency.
#
# All these results are recorded in a table ge
#
# yr	| firstName	| lastName	| constituency	| party	| votes
# ---:|-----------|-----------|---------------|-------|------:
# 2015	| Ian	| Murray	| S14000024	| Labour	| 19293
# 2015	| Neil	| Hay	| S14000024	| Scottish National Party	| 16656
# 2015	| Miles	| Briggs	| S14000024	| Conservative | 8626
# 2015	| Phyl	| Meyer	| S14000024	| Green	| 2090
# 2015	| Pramod	| Subbaraman	| S14000024	| Liberal Democrat	| 1823
# 2015	| Paul	| Marshall	| S14000024	| UK Independence Party	 | 601
# 2015	| Colin	| Fox	| S14000024	| Scottish Socialist Party	| 197
# 2017	| Ian	| MURRAY	| S14000024	| Labour	| 26269
# 2017	| Jim	| EADIE	| S14000024	| SNP	| 10755
# 2017	| <NAME>	| SMITH	| S14000024	| Conservative	| 9428
# 2017	| <NAME>	| BEAL	| S14000024	| Liberal Democrats	| 1388
#

import getpass
import psycopg2
from sqlalchemy import create_engine
import pandas as pd
pwd = getpass.getpass()
engine = create_engine(
    'postgresql+psycopg2://postgres:%s@localhost/sqlzoo' % (pwd))
pd.set_option('display.max_rows', 100)

# ## 1. Warming up
#
# Show the **lastName, party** and **votes** for the **constituency** 'S14000024' in 2017.

ge = pd.read_sql_table('ge', engine)

ge.loc[(ge['constituency']=='S14000024') & (ge['yr']==2017), 
       ['lastname', 'party', 'votes']]

# ## 2. Who won?
#
# You can use the RANK function to see the order of the candidates. If you RANK using (ORDER BY votes DESC) then the candidate with the most votes has rank 1.
#
# **Show the party and RANK for constituency S14000024 in 2017. List the output by party**

a = ge.loc[(ge['constituency']=='S14000024') & (ge['yr']==2017),
       ['party', 'votes']]
(a.assign(rank=a['votes'].rank(ascending=False))
  .sort_values('party'))

# ## 3. PARTITION BY
#
# The 2015 election is a different PARTITION to the 2017 election. We only care about the order of votes for each year.
#
# **Use PARTITION to show the ranking of each party in S14000021 in each year. Include yr, party, votes and ranking (the party with the most votes is 1).**

a = ge[ge['constituency']=='S14000021'].copy()
a['posn'] = (a.groupby('yr')['votes']
              .rank(ascending=False))
a[['yr', 'party', 'votes', 'posn']].sort_values(['party', 'yr'])

# ## 4. Edinburgh Constituency
#
# Edinburgh constituencies are numbered S14000021 to S14000026.
#
# **Use PARTITION BY constituency to show the ranking of each party in Edinburgh in 2017. Order your results so the winners are shown first, then ordered by constituency.**

a = ge[(ge['constituency'].between('S14000021', 'S14000026')) &
       (ge['yr']==2017)].copy()
a['posn'] = (a.groupby('constituency')['votes']
             .rank(ascending=False))
(a[['constituency', 'party', 'votes', 'posn']]
   .sort_values(['posn', 'constituency']))

# ## 5. Winners Only
#
# You can use [SELECT within SELECT](https://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial) to pick out only the winners in Edinburgh.
#
# **Show the parties that won for each Edinburgh constituency in 2017.**

a = ge[(ge['constituency'].between('S14000021', 'S14000026')) & (ge['yr']==2017)].copy()
a['posn'] = a.groupby('constituency')['votes'].rank(ascending=False)
a.loc[a['posn']==1, ['constituency', 'party']].sort_values('constituency')

# ## 6. Scottish seats
#
# You can use **COUNT** and **GROUP BY** to see how each party did in Scotland. Scottish constituencies start with 'S'
#
# **Show how many seats for each party in Scotland in 2017.**

a = ge[(ge['constituency'].str.startswith('S')) &
       (ge['yr']==2017)].copy()
a['posn'] = (a.groupby('constituency')['votes']
              .rank(ascending=False))
(a[a['posn']==1].groupby('party')['yr']
     .count()
     .reset_index()
     .rename(columns={'yr': 'n'}))



StarcoderdataJupyterScriptsDedupFiltered