Learning pandas as a SQL Person: What Tripped Me Up

Published:

By

Years of SQL, one week of pandas. The gotchas that slowed me down and the write-the-SQL-first approach that helped.

Python

The Goal

In the spirit of Hacktoberfest, I dedicate every October to building a project or learning something new. This year it was getting my website updated and running, and posting every week in October. The first week was getting the site back up, and then I decided I had time, so let's learn pandas the right way. I've dabbled in the past, but nothing too in depth. I've spent years doing SQL every day for work, so I wanted to extend those skills and become fluent in pandas, or as fluent as I could get in a few weeks at least.

Finding a way to learn

The first struggle was finding a way to learn pandas. I didn't want to pay for a course, so I checked out what was freely available. I thought 30 Days of Pandas would be a good starting point, but that turned out to be just drills with no teaching. It was not the right starting point for me. I struggled with that for a few days and decided that's not how I wanted to go. Then I found the Kaggle course. It's not advertised as a full in-depth course, but it does teach the basics. However, it had only one example per concept, and the last few questions of every set are a big difficulty jump. It wasn't enough practice for it to really stick or to let me test myself before it moved me onto the next concept. I found myself looking it up the first time, referencing what was taught, and then instead of getting another example or two to practice on without looking it up, it just moved on to the next concept and the cycle continued.

I learn best with five to six reps of one concept. I'll look at a reference the first time, maybe the first two times. Then through spaced repetition, or just a couple of different problems that practice the same concept, I get my five or six reps in. I've found that's the sweet spot for me to remember it well enough to build a flashcard off of what helped me remember the syntax.

Once I figured that out, I took the Kaggle course and extended it with more practice problems. To do that, I needed a dataset. Something you'll probably learn about me through these posts is that I'm a huge board game fan, and one of my favorite board games is Summoner Wars. I like to say it's kind of Magic: The Gathering meets chess. That's not fully true, it's more chess than Magic, but it has the same feel: get stuff on the board and attack the enemy with the goal of knocking their summoner to 0 health. Everything has unique abilities, and you're trying to tactically outmaneuver your opponent like in chess.

Plaid Hat Games (the creators of Summoner Wars) actually posted a stats site this in October, and it made it very easy to pull about a hundred thousand rows of games just from the first page that loads. So I downloaded that CSV locally and decided to do my own analysis and try to match what they're reporting, just to get some practice in with a reference point. I could filter the stats on their site, so I had ways to slice the data different ways and check that I was doing it correctly. I wanted to see if I could reproduce the win rates for each faction among other things.

The frequent stumbling points

There were quite a few stumbling blocks for just a week into learning pandas, and there's still plenty I'm lost on, need clarification on, or just need a lot more practice with.

The first big thing was filtering with two conditions. | and & get evaluated before ==, so something like a == 1 | b == 2 tries to compute 1 | b first. I had to wrap each condition in its own parentheses, which I'm not used to doing in SQL or even regular Python. Anything with a == comparison was messy until I figured out you had to wrap each condition.

Another thing that was hard for me coming from SQL is that a group by doesn't do anything until you aggregate it. SQL is kind of the opposite problem: when you're learning it, you try to throw in an aggregate and it yells at you that you need a GROUP BY. In pandas, if I just threw a group by in there to see my results, it returned a groupby object and nothing else. So I had to figure out how to do a COUNT(), which is usually my first starting point: count everything, grouped by department or whatever you would do in SQL. After a group by, .size() is the equivalent of COUNT() and .count() is the equivalent of COUNT(column). They count differently because one counts nulls and the other skips them. One thing that still trips me up is that plain df.size without the group by gives you every cell in the table, rows times columns.

When trying to find the win rate, I struggled to figure out the right order because everything nests together. I tend to write pandas as a bunch of methods chained one after the other. That's probably not the best for readability, but it's where my brain starts, so I was struggling to figure out what order to put things in. Where in that chain do you group by? Where do you put the WHERE conditions? Where does the SELECT come into play? When calculating win rate, I found out the CASE WHEN has to exist before the group by. So I had to assign it as a column first, then group, so it's available to aggregate after grouping. Seeing groupby earlier in a statement and not as one of the last steps is taking some getting used to.

A cool thing I'm sure I knew and just rediscovered is that if you take the mean of a True/False column, that's the win rate. That was a really neat simplification after I tried to overcomplicate it a time or two.

The results were pretty good. I was able to match what the stats site was reporting, at least initially. The site updates with newer records, so once it moved past my local copy, the numbers no longer matched. But it did match for a while, so I know I was calculating it correctly.

Some other things I ran into: if you use .unique() to get the unique values, it takes you out of pandas entirely and returns a NumPy array. Then you can't do any more pandas operations on top of it. That was annoying. I did not like that. In SQL, a SELECT DISTINCT still leaves you in SQL. You don't suddenly get dropped into a different datatype that SQL can't handle. drop_duplicates() is what you need to get unique values and stay in a DataFrame.

.join() is way pickier than I was hoping it would be. There's no explicit ON condition, and when you do use on=, it only applies to the left side. The right side matches on its index. That breaks my brain a little coming from SQL, and I'm learning .merge() might be the one I lean on more. It's a bit more verbose, but it's more similar to SQL than .join(), which is weird. I'm going to have to retrain my brain on that.

What helped

What I found helpful is to write the SQL first, then read it in the order SQL actually runs. Not SELECT, FROM, WHERE, but FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. The way SQL runs behind the scenes is how you have to think when you work with pandas. It makes sense, but before I fully realized that, I was struggling to figure out the order. SELECT FROM WHERE is so ingrained in me that translating in a different order is still tripping me up a week or two in. When I build chains now, I prep, I group, I pick a column, I aggregate, I filter groups, then I sort.

After several days of doing reps of basic problems to reinforce the concepts, I went back to 30 Days of Pandas. Something I had been stuck on for three days, I solved in ten or twenty minutes, just because I was more familiar with the syntax and the way of thinking. Translating what I would have done in SQL into pandas and following that process helped me unravel the problem a lot easier.

Where do I stand a week in? I'm still very fuzzy on what indexes actually do. When you sort, the row labels stay attached to their rows, so they come out of order, and coming from the SQL world that's crazy. We'll probably deep dive into that in a future post once I've spent a lot more time with it. Nothing's automatic yet. I still refer to the cheat sheets and reference documents I'm making to figure out exact methods. Was it .sort_values or .sort? Just figuring out the right keywords.

I did build a full SQL-to-pandas cheat sheet from my own code. I'll post it shortly after this one goes live so you can see where my first week took me and the type of practice I was doing.

I know pandas is a very powerful tool, especially in the data world. I do see the uses for it and a lot of potential for where I can use it in my day to day, especially for checking data quality before deep diving into SQL analysis. We'll see where this journey takes me. I'm excited for it.

If you came from the SQL world and moved to pandas, I'd love to hear what tripped you up. Feel free to send me a message or a connection request on LinkedIn, and I'm happy to chat about it. And if you came from the pandas world and moved to SQL, I'd love to hear that perspective too.