Musings of a dad with too much time on his hands and not enough to do. Wait. Reverse that.

Author: Brad (Page 18 of 57)

Dad. Technologist. Fan of English poet of John Lillison.

Pulling public data into dataframes

Some of what I write about here is inspired by challenges I encounter at work. Often the hardest part in describing those challenges is substituting public data and scenarios for my work-specific ones. Sites like kaggle.com and wikipedia.org really come to the rescue.

Recently, I had a circumstance where I need to process a dataframe in which one of the columns contained a list of values for each field. I think I came up with a clever way of dealing with that obstacle and would like to discuss it in these pages, but first…what sort of public data can I collect to replicate my scenario? How about some English football?! Let’s take some some football titles–say, the UEFA Champions League champion, the UEFA Europa League champion, and the UEFA Super Cup champion–and build a dataframe that shows which English football clubs have ever won any of these titles.

Step 1: Collect the raw data for each of these titles

I’ve written a few times before on how to use Python to collect public data from the Internet. This time around, I went with a slightly more manual approach. I went to each of the three Wikipedia pages, hit F12 to bring up my developer tools, and used those tools to copy just the HTML code for the data tables I was interested in–the ones listing each club team and the number of times they won the particular title. I simply copied the HTML to three different data files for subsequent processing.

Step 2: Read in the data files

The pandas read_html function is such a time saver here. Here’s the code I came up with to read in my data files:

import pandas as pd
from bs4 import BeautifulSoup
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

%matplotlib inline  # for jupyter notebook
matplotlib.style.use('seaborn')

df_champions = pd.read_html('./data/uefa_champions.txt')[0]
df_champions = df_champions[df_champions.Titles>0]
df_champions['title'] = 'UEFA Champions League champ'

df_europa = pd.read_html('./data/uefa_europa_league.txt')[0]
df_europa = df_europa[df_europa.Winners>0]
df_europa['title'] = 'UEFA Europa League champ'

df_super = pd.read_html('./data/uefa_super.txt')[0]
df_super = df_super[df_super.Winners>0]
df_super['title'] = 'UEFA Super Cup champ'

The df_champions dataframe looks like this:

The last five records in the df_champions dataframe. Which of these are English teams?

These dataframes are looking good, but how do I know which teams are the English teams? Wikipedia identifies each team’s nationality with a flag icon, but pandas isn’t pulling in that data. Time for a little HTML parsing with BeautifulSoup.

Step 3: Collect the names of the English teams

Since pandas didn’t pull in the nationality information, I had to revisit each of the HTML data files and parse out that information with BeautifulSoup:

epl_teams = []
for filepath in ['./data/uefa_champions.txt', './data/uefa_europa_league.txt', './data/uefa_super.txt']:
    with open(filepath, 'r') as f:
        soup = BeautifulSoup(f)

        for th in soup.findAll('th'):
            span = th.find('span', {'class':'flagicon'})
            if span:
                a = span.find('a', {'title':'England'})
                if a:
                    epl_teams.append(th.text.strip())

Step 4: Filter each title list down to just the English teams

With the names of the English teams, I can filter my dataframes down accordingly:

df_champions = df_champions[df_champions.Club.isin(epl_teams)]
df_europa = df_europa[df_europa.Club.isin(epl_teams)]
df_super = df_super[df_super.Club.isin(epl_teams)]

Step 5: Merge the dataframes together

I need to merge my three dataframes into a single one. The pandas merge function did the trick:

df_combo = df_champions[['Club','title']].merge(df_europa[['Club','title']], on='Club', how='outer')
df_combo = df_combo.merge(df_super[['Club','title']], on='Club', how='outer')

And the results:

Merging dataframes with columns of the same name forces pandas to add suffices to those column names

Step 6: Combine the “title” columns together into one

The final step–to just get this public data into a shape to replicate my original problem–is to merge the three “title” columns into a single one. Two lines do the deed:

df_combo['title'] = df_combo.apply(lambda r: [t for t in [r.title_x, r.title_y, r.title] if t is not np.nan], axis=1)
df_combo = df_combo[['Club', 'title']]
A dataframe with a list of values in the “title” column

Phew. That was a fair amount of work just to pull together some public data to replicate one of my work datasets. And the actual code I wrote to analyze a dataframe containing lists in a column? Well, that will have to wait for a future post.

Learning Guitar with Python, Part 1

After many years of just messing around, I’ve started formal guitar lessons this year. A lot of my instruction includes learning the notes on the fret board, the different keys of music, scales, some basic music theory, and so forth. I’ve taken a lot of hand written notes during my instructional sessions and recently started transcribing a lot of those digitally. It occurred to me that Jupyter Notebook and Python might be a fantastic way to depict some of the concepts I’m learning. So, here is Part 1 of some of my guitar notes with the help of Jupyter Notebook and Python.

The 12 Keys

I won’t take the time to explain the notes and basic pattern in music as that information can be found all over the internet. The first idea I wanted to construct was a grid of the 12 keys and the notes within each key. My instructor and I have also talked a lot about the relative minor in each major key, so I wanted my graphic to convey that point, too. I put together this code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

# make up my list of notes
chromatic_scale_ascending = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
# since I usually start on the low E string, rearrange the notes starting on E
scale_from_e = (chromatic_scale_ascending + chromatic_scale_ascending)[4:16]

# the scale pattern:
# root, whole step, whole step, half step, whole step, whole step, whole step, half step
key_steps = [2, 2, 1, 2, 2, 2]  # on the guitar, a whole step is two frets
major_keys = []
for root in scale_from_e:
    three_octaves = scale_from_e * 3
    steps_from_root = three_octaves.index(root)
    major_scale = [root]
    # construct the unique notes in the scale
    for step in key_steps:
        steps_from_root += step
        major_scale.append(three_octaves[steps_from_root])
        
    # span the scale across 3 octaves
    major_keys.append(major_scale * 2 + [root])
    
df_major_keys = pd.DataFrame(major_keys)
df_major_keys.columns = df_major_keys.columns + 1  # start counting notes at 1 instead of 0

# use this function to highlight the relative minor scales in orange
def highlight_natural_minor(data):
    df = data.copy()
    df.iloc[:,:] = 'font-size:20px;height:30px'
    df.iloc[:,5:13] = 'background-color: lightgray; font-size:20px'
    return df

print('The 12 keys and the notes within them:')
df_major_keys.style.apply(highlight_natural_minor, axis=None)

Which produced this handy graphic:

The 12 keys and their notes

For simplicity, I used sharps in my keys instead of flats. The highlighted part of the table marks the relative minor portion of the major key.

The notes of the fret board

Probably one of the best ways to learn the notes on your guitar’s fret board is to trace out the fret board on a blank piece of paper and start filling in each note by hand. Do that a few hundred times and you’ll probably start remembering the notes. Being lazy, though, I wanted to have my computer do that work for me. Here’s the code I came up with to write out the fret board:

standard_tuned_strings = ['E', 'A', 'D', 'G', 'B', 'E']
chromatic_scale_ascending = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
col_names = ['Low E', 'A', 'D', 'G', 'B', 'High E']
fretboard_notes = []

for string in standard_tuned_strings:
    start_pos = chromatic_scale_ascending.index(string)
    fretboard_notes.append((chromatic_scale_ascending + chromatic_scale_ascending)[start_pos+1:start_pos+13])

df_fretboard = pd.DataFrame(np.array(fretboard_notes).T, index=np.arange(1, 13), columns=col_names)
df_fretboard.index.name = 'fret'

def highlight_select_frets(data):
    fret_markers = [2, 4, 6, 8, 11]
    df = data.copy()
    df.iloc[:,:] = 'font-size:20px'
    df.iloc[fret_markers,:] = 'background-color: lightgray; font-size:20px'
    return df

df_fretboard.style.apply(highlight_select_frets, axis=None)
Notes on the guitar fret board (1st through 12th fret, standard tuning)

More notes to come, so stay tuned! (Puns intended)

Iterating over a date range

I leverage a number of different programming and scripting tools. Recently, I found myself in a situation where I had to write code to loop through a range of dates to do some operations, by month, in not one, not two…but three different languages: Scala, Python, and Bash. The coding principles are the same across the technologies, but the syntax sure is different.

Here are code examples in four technologies–I threw in PowerShell for good measure–for looping through a range of dates. I loop by month, but these could easily be adapted to loop by day or year or whatever increment fits your needs.

Scala

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Date

val start = LocalDate.of(2020, 1, 1) // inclusive in loop
val end = LocalDate.of(2020, 9, 1) // excluded from loop

val template = "This loop is for Year %1$d and Month (zero padded) %2$s \n"

val date_range = Iterator.iterate(start) { _.plusMonths(1) }.takeWhile(_.isBefore(end))
while(date_range.hasNext){
	val d = date_range.next
	val s = template.format(d.getYear, d.format(DateTimeFormatter.ofPattern("MM")))
	print(s)
}

Python

import datetime
import calendar

start = datetime.date(2020, 1, 1)
end = datetime.date(2020, 9, 1)
template = "This loop is for Year {0} and Month (zero padded) {1:%m}"

while start != end:
	s = template.format(start.year, start)
	print(s)
	days_in_month = calendar.monthrange(start.year, start.month)[1]
	start = start + datetime.timedelta(days=days_in_month)
	

Bash

start=2020-1-1
end=2020-9-1

while [ "$start" != "$end" ]; do
	s="`date -d "$start" +"This loop is for Year %Y and Month (zero padded) %m"`"
	echo s
	start=$(date -I -d "$start + 1 month")
done

PowerShell

$start = get-date "2020-1-1"
$end = Get-Date "2020-9-1"

while($start -ne $end){
    "This loop is for Year {0:yyyy} and Month (zero padded) {0:MM}" -f $start
    $start = $start.AddMonths(1)
}
« Older posts Newer posts »

© 2024 DadOverflow.com

Theme by Anders NorenUp ↑