Lesson 46 · Real-World Data Analytics
Net Balance Tables in Pandas: Chess Players Changing Countries | Python Data Analytics #46
A sixth completely different competitive activity in this sports analytics domain. A real FIDE dataset tracking every real chess player who changed national…
- CourseReal-World Data Analytics
- Lesson46 of 100
- Video15 min
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- chess_transfers.csv preview60.8 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 46: Real FIDE Chess Federation Transfer Analysis#
- Video forty-six of the hundred-video real-world data analytics series, a sixth completely different competitive activity in this sports analytics domain.
- A real FIDE dataset tracking every real chess player who changed national federations from 2000 through 2015.
- Let's get into it.
This lesson is for learners who can load a CSV with pandas and want practice answering questions about movement between groups. The business question is simple to state: which national chess federations attract players, which ones lose them, and has the flow changed over time? The dataset is a real FIDE (the international chess federation) record of players who switched national federations between 2000 and 2015. Each row is one transfer, and the columns that matter are ID (the player's FIDE identifier), Federation (the country they moved to), Form.Fed (the country they left) and Transfer Date.
The same thinking applies to customer churn between suppliers, staff moving between departments or users switching between products.
In this lesson you will:
- count incoming and outgoing transfers per federation and combine them into a net balance
- turn a text date into a year and track volume over time
- spot players who appear more than once and check for duplicate rows
- find the most common origin and destination pairs
Prerequisites: you should be comfortable with value_counts(), boolean masks and basic matplotlib charts. Earlier lessons in the series cover these if you need a refresher.
Part 1: A Real Chess Migration Dataset#
Before any analysis you need to know how much data you are working with. The code imports pandas, numpy and matplotlib, reads chess_transfers.csv into a DataFrame called transfers and then checks .shape, which returns a (rows, columns) pair. The output is (829, 5): 829 transfers described by just five columns. That is small enough to reason about by hand, which makes it a good dataset for checking every result against common sense. Note the row count now, because a later sanity check confirms it has not changed.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
transfers = pd.read_csv('chess_transfers.csv')
transfers.shape
Part 2: Real Data Preview#
Knowing the column names exactly, including spaces and dots, saves you from typos later. The code calls transfers.head(5) and then transfers.columns.tolist(), but Jupyter only displays the last expression, so the output is just the list of names: url, ID, Federation, Form.Fed and Transfer Date. Two names need care. Form.Fed contains a dot, so you must use bracket access transfers['Form.Fed'] rather than dot access, and Transfer Date contains a space for the same reason. If you want to see the sample rows too, run head(5) on its own.
transfers.head(5)
transfers.columns.tolist()
Part 3: Real Missing Data Check#
Missing values change what your counts mean, so check them before you count anything. transfers.isna() marks every empty cell as True, and .sum() adds those up column by column, because True counts as 1. The output shows that four columns are complete and only Form.Fed has gaps, with 9 missing values. A missing former federation is unusual for a transfer, so it deserves an explanation rather than a quick dropna(). Later in the lesson these 9 rows are interpreted as players who were new to FIDE.
transfers.isna().sum()
Part 4: Real Top Gaining Federations#
The first real question is which countries attract the most chess players. value_counts() on the Federation column counts how many times each destination appears and sorts from highest to lowest, and .head(5) keeps the top five. The output shows the USA well ahead with 82 incoming transfers, followed by Germany (GER) with 51, Canada (CAN) with 41, Spain (ESP) with 36 and France (FRA) with 34. Keep in mind this counts arrivals only: a federation can attract many players and still lose even more.
top_gainers = transfers['Federation'].value_counts().head(5)
top_gainers
Part 5: Real Top Losing Federations#
Arrivals are only half the picture, so this step counts departures. The same value_counts().head(5) pattern is applied to Form.Fed, the federation each player left. Russia (RUS) loses the most with 70, then Ukraine (UKR) with 52, Germany with 40, England (ENG) with 32 and France with 31. Notice that Germany and France appear on both the gainers and losers lists. That is a hint that raw counts in one direction can mislead, and it sets up the net balance calculation later in the lesson. Missing values in Form.Fed are excluded from value_counts() by default.
top_losers = transfers['Form.Fed'].value_counts().head(5)
top_losers
Part 6: Real Top Gainers Chart#
A ranked bar chart makes the top gainers easier to compare at a glance than a printed table. The code creates a figure with plt.subplots, sorts the counts with sort_values() so the biggest bar lands at the top, and draws a horizontal bar chart with kind='barh'. It labels the axis, sets a title, and saves the image with plt.savefig before plt.close() closes it, so no chart appears in the notebook itself. When you open top_gaining_federations.png, look for how far the USA bar extends beyond the others. Sorting before plotting is a small habit that makes ranked charts much easier to read.
fig, ax = plt.subplots(figsize=(8, 6))
top_gainers.sort_values().plot(kind='barh', ax=ax, color='seagreen')
ax.set_xlabel('Real Number of Incoming Transfers')
ax.set_title('Real Top 5 Chess Federations by Incoming Transfers, 2000-2015')
plt.tight_layout()
plt.savefig('top_gaining_federations.png', dpi=100)
plt.close()
Part 7: Real United States Transfers#
Looking at a single federation in both directions shows why one-sided counts are incomplete. The code builds two boolean masks, one where Federation equals 'USA' and one where Form.Fed equals 'USA', and .sum() counts the True values in each. The output is (82, 30): 82 players joined the US federation and 30 left it. So the USA is not only the most popular destination, it also keeps a clear surplus of 52 players. This in-versus-out comparison is exactly what the net balance step later does for every federation at once.
usa_in = (transfers['Federation'] == 'USA').sum()
usa_out = (transfers['Form.Fed'] == 'USA').sum()
usa_in, usa_out
Part 8: Real Transfer Year Extraction#
Dates stored as text cannot be grouped by year, so they need converting first. pd.to_datetime parses the Transfer Date strings using format='%m/%d/%y', which means month, day and a two-digit year, and .dt.year pulls out the year as a number into a new transfer_year column. The output shows the first five rows side by side, for example 12/15/00 becoming 2000. Supplying an explicit format is safer than letting pandas guess, because a date like 1/2/03 could otherwise be read as day first or month first.
transfers['transfer_year'] = pd.to_datetime(transfers['Transfer Date'], format='%m/%d/%y').dt.year
transfers[['Transfer Date', 'transfer_year']].head(5)
Part 9: Real Transfers by Year#
With a year column in place you can see whether transfer activity is rising, falling or steady. value_counts() counts transfers per year, and .sort_index() reorders the result by year instead of by count, which is what you want for a time series. The output runs from only 6 transfers in 2000 to 82 in 2014 and 75 in 2015, with most years in between sitting in the 40 to 60 range. The very low 2000 figure may reflect how the records were collected rather than real behaviour, so treat the first year with some caution.
year_counts = transfers['transfer_year'].value_counts().sort_index()
year_counts
Part 10: Real Transfer Year Trend Chart#
A line chart shows the shape of a time series much better than a column of numbers. The code plots year_counts.index (the years) against year_counts.values (the counts), with marker='o' adding a dot for each year so individual points stay visible. Axis labels and a title are set, and the chart is saved to transfers_by_year.png and then closed, so nothing displays in the notebook. When you open the image, look for the steep climb out of 2000, the up-and-down pattern through the middle years and the jump in 2014 and 2015.
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(year_counts.index, year_counts.values, marker='o', color='darkred')
ax.set_xlabel('Real Year')
ax.set_ylabel('Real Number of Transfers')
ax.set_title('Real FIDE Federation Transfers by Year, 2000-2015')
plt.tight_layout()
plt.savefig('transfers_by_year.png', dpi=100)
plt.close()
Part 11: Real Repeat Transfer Players#
Some players change federation more than once, and counting them tells you how much of the movement comes from a small group. value_counts() on ID counts rows per player. Comparing that with > 1 gives True for every player who appears more than once, and .sum() counts those Trues. The output is 173 players with more than one row. Be careful how you read this: the duplicate check later in the lesson finds repeated rows, so some of these 173 may be the same transfer recorded twice rather than genuine second moves.
id_counts = transfers['ID'].value_counts()
repeat_players = (id_counts > 1).sum()
repeat_players
Part 12: Real Most Frequent Transferer#
After counting repeat players it is natural to ask how extreme the most active case is. id_counts.max() returns the largest number of rows held by any single player ID. The output is 4, so no player appears more than four times in the dataset. That is a useful upper bound: it tells you no single person dominates the data. If you want to know who that player is, id_counts.idxmax() would return the ID rather than the count.
most_transfers = id_counts.max()
most_transfers
Part 13: Real Net Federation Gain/Loss#
The net balance answers the real question: after arrivals and departures, which federations end up ahead? The code counts gains from Federation and losses from Form.Fed, then uses gains.subtract(losses, fill_value=0). The fill_value=0 matters, because a federation that appears in only one of the two lists would otherwise get NaN instead of a number. sort_values(ascending=False) puts the biggest winners first. The output shows the USA on +52, Canada +30, Turkey (TUR) +27, Czech Republic (CZE) +23 and Austria (AUT) +21. The values show as decimals such as 52.0 because the fill step converts them to floats.
gains = transfers['Federation'].value_counts()
losses = transfers['Form.Fed'].value_counts()
net = (gains.subtract(losses, fill_value=0)).sort_values(ascending=False)
net.head(5)
Part 14: Real Biggest Net Losers#
The other end of the same sorted series shows who loses the most players overall. Because net is sorted from highest to lowest, .tail(5) returns the five lowest values. Russia has the largest deficit at -41, then Ukraine at -37, Cuba (CUB) at -24, Serbia (SRB) at -16 and Romania (ROU) at -15. Compare this with the raw departures list: Germany lost 40 players but does not appear here, because its arrivals largely made up for it. This is why net figures are usually more informative than one-way counts.
net.tail(5)
Part 15: Real Net Balance Chart#
Putting winners and losers on one chart shows the imbalance more clearly than two separate tables. The code joins net.head(5) and net.tail(5) with pd.concat, sorts the result, and draws horizontal bars. The color argument uses .apply with a small lambda that returns 'seagreen' for values of zero or more and 'firebrick' for negatives, so each bar is coloured by its sign. The chart is saved to net_federation_balance.png and closed. When you open it, look for the split around zero, with the USA longest on the positive side and Russia longest on the negative side.
fig, ax = plt.subplots(figsize=(10, 6))
top_net = pd.concat([net.head(5), net.tail(5)])
top_net.sort_values().plot(kind='barh', ax=ax, color=top_net.sort_values().apply(lambda v: 'seagreen' if v >= 0 else 'firebrick'))
ax.set_xlabel('Real Net Transfers, Gains Minus Losses')
ax.set_title('Real Biggest Net Winners and Losers in Chess Federation Transfers')
plt.tight_layout()
plt.savefig('net_federation_balance.png', dpi=100)
plt.close()
Part 16: Real Same-Federation Sanity Check#
A transfer from a federation to itself would be a data error, so it is worth confirming none exist. The code compares Federation and Form.Fed row by row with ==, which returns True where they match, and .sum() counts the matches. The output is 0, so every recorded transfer genuinely moves between two different federations. Rows where Form.Fed is missing compare as False, so they do not affect this count. Quick logical checks like this are cheap and catch problems that summary statistics miss.
same_federation = (transfers['Federation'] == transfers['Form.Fed']).sum()
same_federation
Part 17: Real New-to-FIDE Players#
Earlier you found 9 missing values in Form.Fed. This step gives them a meaning. A player with no former federation most likely had not been registered with any national federation before, so they were new to FIDE rather than transferring. The code uses isna().sum() on that column, and the output confirms 9 such players. Recording this count in its own variable, new_to_fide, makes it reusable later. Explaining missing values in plain language like this is better than silently dropping them.
new_to_fide = transfers['Form.Fed'].isna().sum()
new_to_fide
Part 18: Real Unique Federations Involved#
Knowing how many federations are involved gives context for all the rankings so far. The code stacks the Federation and Form.Fed columns into one long series with pd.concat, removes missing values with .dropna(), and counts distinct codes with .nunique(). The output is 119 federations that sent or received at least one player. With that many countries involved, a top five that includes the USA on 82 arrivals shows how concentrated the incoming flow is. Combining both columns matters, because some federations may only ever appear on one side.
all_federations = pd.concat([transfers['Federation'], transfers['Form.Fed']]).dropna().nunique()
all_federations
Part 19: Real Busiest Transfer Year#
Pinning down the peak year turns the trend chart into a precise fact. On the yearly counts, idxmax() returns the index label (the year) of the largest value, and max() returns the value itself. The output is (2014, 82), so 2014 was the busiest year with 82 transfers. The numpy type labels in the output, such as np.int32, are just how pandas reports the number types and do not change the values. Remember that idxmax() gives the label, not the position.
busiest_year = year_counts.idxmax()
busiest_year_count = year_counts.max()
busiest_year, busiest_year_count
Part 20: Real Quietest Transfer Year#
The quietest year is the mirror image of the busiest one. Here idxmin() returns the year with the lowest count and min() returns that count. The output is (2000, 6): only 6 transfers were recorded in 2000, far below any later year. A first year this low often means the records start partway through or were less complete at the beginning, so be careful about reading it as a real dip in player movement. Always ask whether an extreme value reflects behaviour or data collection.
quietest_year = year_counts.idxmin()
quietest_year_count = year_counts.min()
quietest_year, quietest_year_count
Part 21: Real Duplicate Row Check#
Duplicate rows can quietly inflate every count you have made so far. duplicated(subset=['ID', 'Transfer Date', 'Federation']) marks a row as True when an earlier row has the same player, date and destination, and .sum() counts them. The output is 157 such repeated rows, which is a large share of 829. The notebook does not remove them, so treat the earlier counts, especially the 173 repeat players, with this in mind. A good habit is to inspect a few duplicates with keep=False to see whether they are true copies or separate records.
transfers.duplicated(subset=['ID', 'Transfer Date', 'Federation']).sum()
Part 22: Real First Decade vs Second Half#
Splitting the period in two is a quick way to test whether activity grew over time without fitting a model. The code builds two boolean masks on transfer_year, one for 2007 and earlier and one for after 2007, and .sum() counts each. Each half covers eight years. The output is (353, 476), so the second half of the period saw noticeably more transfers than the first. This matches what the yearly chart shows, with the busiest years at the end of the range.
early = (transfers['transfer_year'] <= 2007).sum()
late = (transfers['transfer_year'] > 2007).sum()
early, late
Part 23: Real Top Transfer Route#
Individual routes show where players actually travel, which federation totals alone cannot reveal. The code first drops rows with no former federation using dropna(subset=['Form.Fed']), then groups by the pair of Form.Fed and Federation and uses .size() to count rows per pair. Sorting descending gives the most common routes. The output shows Serbia to Bosnia and Herzegovina (SRB to BIH) and Russia to Germany (RUS to GER) tied on 16, then France to Monaco (FRA to MNC) on 14, Ukraine to Germany on 12 and SCG to Croatia on 10. Several routes link neighbouring countries or former shared states.
routes = transfers.dropna(subset=['Form.Fed']).groupby(['Form.Fed', 'Federation']).size().sort_values(ascending=False)
routes.head(5)
Part 24: Saving the Real Enriched Dataset#
Saving your work means the new transfer_year column is available for the next analysis without rerunning everything. to_csv writes the DataFrame to chess_transfers_enriched.csv, and index=False stops pandas adding an extra unnamed index column. The code then reads the file back and compares shapes, and the output True confirms the saved file has the same rows and columns. Forgetting index=False is a common mistake that adds a stray column every time you save and reload.
transfers.to_csv('chess_transfers_enriched.csv', index=False)
reloaded = pd.read_csv('chess_transfers_enriched.csv')
reloaded.shape == transfers.shape
Part 25: Real Sanity Check, Row Count#
A row count check guards against accidental filtering or duplication during the analysis. The code compares len(transfers) with the original 829, and the output True confirms nothing has been added or removed. Adding columns does not change the number of rows, so this is what you would expect here. Checks like this are worth keeping at the end of a notebook, because they fail loudly if a future edit changes the data unexpectedly.
len(transfers) == 829
Part 26: Real Sanity Check, Year Range#
This check confirms the date conversion produced sensible years. The code tests that the smallest transfer_year is at least 2000 and the largest is at most 2015, joined with Python's and. The output np.True_ means both conditions hold, so every year falls inside the stated period. If the date format had been wrong, for example reading two-digit years incorrectly, this kind of check would catch it straight away.
transfers['transfer_year'].min() >= 2000 and transfers['transfer_year'].max() <= 2015
Part 27: Real Sanity Check, No Same-Federation Transfers#
This step turns an earlier finding into an explicit test. It simply checks that the same_federation count from the earlier step equals zero. The output np.True_ confirms that no row lists the same federation as both origin and destination. Writing findings as True or False tests like this makes the notebook self-checking: if the data source changes, you will know immediately which assumption broke.
same_federation == 0
Part 28: Real Sanity Check, Missing Values Explained#
The last sanity check confirms that the missing values have been fully explained. It compares the number of missing Form.Fed values with the new_to_fide count stored earlier, and the output np.True_ shows they match. In other words, every gap in that column is accounted for by the new-to-FIDE interpretation, with nothing left unexplained. Linking each missing value to a reason is good practice before you share results with anyone else.
transfers['Form.Fed'].isna().sum() == new_to_fide
Part 29: Real Top Finding Print#
Analysis is only useful once you can state a finding in a plain sentence. The code takes the first label from top_gainers with .index[0] and the matching count with .iloc[0], then drops both into an f-string. The printed output reads that the USA gained the most players of any federation, with 82 incoming transfers. Building the sentence from variables rather than typing the numbers means it stays correct if the data is updated.
top_gainer_fed = top_gainers.index[0]
top_gainer_count = top_gainers.iloc[0]
print(f'{top_gainer_fed} gained the real most players of any federation in this dataset, with {top_gainer_count} real incoming transfers.')
Part 30: Real Recap Print#
A short recap sentence pulls the main results together for a reader who will not look at the code. The f-string combines the total row count, the busiest year and its count, and the number of repeat players. The printed output says that across 829 transfers from 2000 to 2015, the busiest year was 2014 with 82 transfers and 173 players switched federations more than once. Remember the duplicate check when quoting that last figure, since some repeats may be duplicated records.
print(f'Across {len(transfers)} real federation transfers from 2000 to 2015, the busiest year was {busiest_year} with {busiest_year_count} transfers, and {repeat_players} real players switched federations more than once.')
Wrap-Up: What You Learned#
- This real dataset covers eight hundred twenty-nine real FIDE federation transfers from 2000 through 2015, with real missing values honestly explained by real new-to-FIDE players.
- Real federation transfer volume genuinely varied year to year, with a real clear busiest year standing out across this real fifteen-year span.
- A real small number of real players switched federations more than once, and this real dataset let us count exactly how many.
- This real domain has now covered six genuinely different competitive activities, basketball, tennis, baseball, football, soccer, and chess, using six real independently sourced datasets.
- Every real number in this lesson traces back to genuinely real, complete FIDE transfer records, the same honest-sourcing standard carried through every domain so far.
- Next video: a real Major League Baseball foul ball safety dataset, continuing this domain with a return to baseball from a completely different angle.
Practice on your own
- Remove duplicates with
transfers.drop_duplicates(subset=['ID', 'Transfer Date', 'Federation']), then rerun the top gainers, net balance and repeat-player counts. Note which figures change and by how much. - Pick one federation from the routes output, such as Germany, and list the top three federations it receives players from and the top three it sends players to, using boolean filters and
value_counts(). - Build a yearly net balance for the USA: count arrivals and departures per
transfer_yearwithgroupby, subtract one from the other, and plot the result as a line chart.
The next lesson in the series returns to baseball with a real Major League Baseball foul ball safety dataset, looking at the sport from a completely different angle. Watch the video walkthrough of this lesson if any step felt unclear.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



