Chuck Grimmett

Data Science

Taxonomies

  • Many-to-Many Relationships in Relational Data Models

    Many-to-Many Relationships in Relational Data Models

    Today I learned about Many-to-Many relationships in relational data models

    • A many-to-many relationship is a type of cardinality that refers to the relationship between two entities A and B in which A may contain a parent instance for which there are many children in B and vice versa.
    • For example, a recipe may have many ingredients and a specific ingredient may be used in many recipes.
    • In SQL, this relationship is handled by an associative table. The primary key for this type of table is composed of two different columns, both of which reference columns in other tables that you are associating together.
    • It is a good convention to name these associative tables by how they reference each other: Table1_Table2
    • A SELECT statement on an associative table usually involves JOINing the main table with the associative table.
    • If you don’t want to run these JOINs every time, create a view first. A view is a virtual table based on the result-set of an SQL statement. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

    Example SQL for creating an associative table:

    CREATE TABLE recipes_ingredients (     RecipeID INT(11) REFERENCES Recipes (RecipeID),     IngredientID INT(11) REFERENCES Ingredients (IngredientID),     PRIMARY KEY (RecipeID, IngredientID) )
  • Trifacta Wrangler

    Trifacta Wrangler

    Trifacta Wrangler

    Trifacta Wrangler is a free program (currently in beta) that helps you clean up data sets and gives you a first cut at basic analysis. It is great for quickly turning messy data into structured, manageable formats.

    Trifacta Wrangler

    In the past few days I’ve used it to analyze huge log files and turn messy JSON in structured CSVs that I could import into SQL.

    Quick tips:

    • splitrows always has to come first. The program usually tries to split by \n (new line) first, but that doesn’t always work for JSON. Try splitting by something like },{, or do a quick find and replace ( },{ for }|||{ ) and do the split by ||| if you want to keep the curly brackets for an unnest.
    • unnest is very powerful for splitting out JSON values out into separate columns titled by their keys.
    • flatten works better than unnest in cases where the JSON does not have keys. It creates new rows and repeats other values in adjacent columns to keep the relation. This works well if you have an ID column and are going to eventually stuff things into a relational database.

    Here is documentation for the Transforms.

  • Using Word Frequency Charts for Better Word Clouds

    Using Word Frequency Charts for Better Word Clouds

    Word clouds

    Data scientists notoriously hate word clouds. Besides for figuring out what the top 2-3 words are (because they are the biggest), it is difficult to see how much one word is used relative to another. Unfortunately, clients and non-data people love word clouds and sometimes insist on them. What is a self-respecting data nerd to do?

    Pair it a word frequency chart!

    The easiest way to do this is by using Python’s counter:

    Counter(words).most_common()

    Then you can use your favorite charting tool to make a bar chart of the results. I prefer D3.js.

    Results

    Word Frequency Chart

    Word Cloud

    If you see both together, you get a better understanding of the words being used. Of course, a single word doesn’t always capture sentiment. They can be helpful in smaller data sets, but sometimes common phrases are more helpful in larger data sets. For common phrases, use n-gram analysis.

    For more on visualizing text, check out episode 62 of the Data Stories podcast and the Text Visualization Browser.

  • Reading CSVs, counting, lambda expressions, and plotting with Python

    Reading CSVs, counting, lambda expressions, and plotting with Python

    Today I learned a lot in Python

    Get current directory

    import os os.getcwd()

    Reading CSVs in Python

    import csv with open('/photo_dates_location.csv') as f:     reader = csv.reader(f, delimiter=',', quotechar='"')     reader.next() #skip header     day_csv = [row[0] for row in reader]

    Counting in Python

    Using Counter to create a list of unique items and counts by appending items to the lists:

    import counter days = [] count = [] for (k,v) in Counter(day_csv).iteritems():     days.append(k)     count.append(v)

    Ordering lists with a lambda expression

    According to Eric Davis the lambda expressionArchived Link is a good way to make quick expressions on the fly for organizing things like the Counter lists:

    day_number = { 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7 } days_sorted = sorted(Counter(day_csv).iteritems(), key=lambda e: day_number[e[0]])

    Plotting with Python

    Given that the lists days and count are built above by the Counter(), you can pass them to matplotlib for charting:

    from matplotlib import pyplot as plt  ######## Bar Chart ######## xs = [i + 0.1 for i, _ in enumerate(days)] plt.bar(xs, count) plt.ylabel("Number of photos taken") plt.title("Photo frequency by day") plt.xticks([i + 0.5 for i, _ in enumerate(days)], days) plt.savefig('img/weekdays_bar.png') plt.clf()  ######## Pie chart ######## colors = ['red', 'orange', 'green', 'purple', 'lightcoral', 'lightskyblue', 'yellowgreen'] explode = [0, 0, 0, 0, 0, 0.1, 0] plt.pie(count, explode=explode, labels=days, colors=colors, autopct='%1.1f%%') plt.axis('equal') plt.suptitle("Percent of total photos taken on a given day of the week", fontsize=18) plt.savefig('img/weekdays_pie.png')
    • If you don’t want to save the images, you could just show them instead with plt.show()
    • plt.clf() clears the figure so you can plot something else on it. Otherwise you’d need to close it before continuing. plt.close() can do that.

    Depending on the source CSV, the above creates these two charts: Photos by day of week count Photos by day of week percentage

  • Dealing with Files in AppleScript and Conditional Counts in Excel

    Dealing with Files in AppleScript and Conditional Counts in Excel

    I took a 10-day break from my TILs and now I’m reinvigorated and back on track. In the past 10 days I spent a lot of time doing things I already knew how to do, but I also worked on a small project related to data visualization to see if I could apply some things I learned over the past few months. The result was my recent blog post on Steph Curry’s stats.

    A new project

    I got a lot of good feedback on Facebook on some more things I can explore (and about how little I understand basketball.) I decided to work on another personal project to apply some of the data science I’ve been learning by reading Joel Grus’s Data Science from Scratch. I decided to find some data (photo dates and locations), extract it (AppleScript), format it (grep FTW), analyze it (forthcoming in Excel and Python), then visualize the insights (Python and/or D3). You can follow my progress on GitHub.


    Dealing with files in AppleScript

    AppleScript natively deals with file paths with colons: Macintosh HD:usr:local:bin: If you get a file path then want to pass it to the shell, you’ll first need to turn it into a POSIX path:

    set a to "Macintosh HD:usr:local:bin:"  set p to POSIX path of a     -- Output: "/usr/local/bin/"

    If you want to create a file in the same folder as a script you are running, you might have to jump back and forth between AppleScript paths and POSIX paths because it is easier to make files by using the command do shell script. Notice the use of quoted form of, which quotes the file path and keeps you clear of pesky errors caused by characters in the path that need to be escaped:

    -- Creating the file in the same folder as this script set scriptPath to POSIX path of ((path to me as text) & "::") do shell script "> " & quoted form of scriptPath & "photo_dates_location.csv"

    Then if you want to get the path to the file you just created and make an it an alias to reference later:

    set filePath to ((path to me as Unicode text) & "::") & "photo_dates_location.csv" set theFile to filePath as alias

    Conditional counting in Excel

    Suppose you have a [spreadsheet full of photos, the date they were taken, and the days of the week they were taken on] (https://github.com/cagrimmett/apple_photos_analysis) and you want to count how many were taken on Monday, Tuesday, etc. Then you’d use the function COUNTIFS(range,argument) to work it out.

    Example: Suppose I have the days of the week in column A and cell H2 contained the word I was looking for, Monday. Then my formula would be:

    =COUNTIFS(A2:A8500,H2) 

    I quickly repeated this for the cells that contained the values for the other days of the week and got instant results:

    Day Count
    Monday 900
    Tuesday 906
    Wednesday 1079
    Thursday 1082
    Friday 1186
    Saturday 1918
    Sunday 1331