> ## Content Index
> Fetch the complete content index at: https://www.bambooweekly.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Bamboo Weekly #88: Hot summers (solutions)
- URL: https://www.bambooweekly.com/bw-88-hot-summers-solution/
- Published: 2024-10-17T15:00:31.000Z
- Updated: 2026-10-18T06:00:07.000Z
- Description: Get better at: Excel files, multi-indexes, renaming columns, grouping, and plotting.
- Author: Reuven M. Lerner
- Tags: excel, multi-index, renaming-columns, grouping, plotting

This week, we looked at a data set that discussed the temperature from June, July, and August of this year, showing how much hotter it was than usual. The data came from Climate Central ([https://www.climatecentral.org](https://www.climatecentral.org/?ref=bambooweekly.com)), an organization aimed at explaining climate change to the general public, whose recently released report showed that this summer was particularly hot.

I heard the CEO of Climate Central, Ben Strauss, on last week's Slate Political Gabfest podcast ([https://slate.com/podcasts/political-gabfest/2024/10/election-kamala-harris-donald-trump-vote-hurricane-milton-helene-climate-change-legal-win](https://slate.com/podcasts/political-gabfest/2024/10/election-kamala-harris-donald-trump-vote-hurricane-milton-helene-climate-change-legal-win?ref=bambooweekly.com)). He said, among other things, that the temperature of ocean water is rising to never-before-seen levels, leading in part to the extremely destructive hurricanes we've seen over the last few weeks.

The data all points to climate change as the reason for increased temperatures. But it would seem that meterologists who mention that as a reason for the huge storms are receiving threats ([https://www.nytimes.com/2024/10/14/us/meteorologists-threats-conspiracy-theories-hurricanes.html?unlocked\_article\_code=1.SU4.uwM2.zFc50u9q7LVB&smid=url-share](https://www.nytimes.com/2024/10/14/us/meteorologists-threats-conspiracy-theories-hurricanes.html?unlocked%5Farticle%5Fcode=1.SU4.uwM2.zFc50u9q7LVB&smid=url-share&ref=bambooweekly.com)).

### Data and seven questions

This week, we'll look at the data set from Climate Central. Their summary of the data is from this page:

[https://www.climatecentral.org/report/people-exposed-to-climate-change-june-august-2024](https://www.climatecentral.org/report/people-exposed-to-climate-change-june-august-2024?ref=bambooweekly.com)

The data itself can be downloaded via the "Download data" link at the bottom of the page (i.e., the final bullet point), which links to the following URL:

[https://assets.ctfassets.net/cxgxgstp8r5d/3YePNai47RE3n0k0mQtuAf/ff0a98edfa5cac0f837534ab9b72cd2a/Climate\_Central\_global\_temperature\_attribution\_data\_June-August\_2024.xlsx](https://assets.ctfassets.net/cxgxgstp8r5d/3YePNai47RE3n0k0mQtuAf/ff0a98edfa5cac0f837534ab9b72cd2a/Climate%5FCentral%5Fglobal%5Ftemperature%5Fattribution%5Fdata%5FJune-August%5F2024.xlsx?ref=bambooweekly.com)

Here are my detailed solutions to the seven questions I asked this week. As usual, a link to my Jupyter notebook is at the bottom of the post.

### Read the Excel file into a Pandas data frame. We want a three-level multi-index, with the continent, region, and country names.

We'll start by loading Pandas:

```python
import pandas as pd
```

To read the Excel file into a data frame, we can use [read\_excel](https://www.bambooweekly.com/pandas-read-excel/): 

```python
filename = 'Climate_Central_global_temperature_attribution_data_June-August_2024.xlsx'

df = pd.read_excel(filename)
```

That works fine, but I asked you to create a data frame with a three-level multi-index. When using [read\_csv](https://www.bambooweekly.com/pandas-read-csv/), we can pass the `index_col` keyword argument. This tells the method which column (a string or integer) or columns (a list of strings, or a list of integers) should be used for the index.

`read_excel` also has an `index_col` keyword argument, and I imagined that I could similarly give it a list of strings. But no, it turns out that in `read_excel`, you pass `index_col` an integer (for a one-column index) or a list of integers (for a multi-index). I ended up with the following:

```python
filename = 'Climate_Central_global_temperature_attribution_data_June-August_2024.xlsx'

df = pd.read_excel(filename,
                  index_col=[23,24,0])                  
```

The result was a 218-row, 23-column data frame.

### The column names are rather long. Shorten or remove repetitive (or unnecessary) text. For example, you can replace the text "Climate Shift Index level 2 (heat made 2x more likely by climate change)" with "CS2".

I was quite surprised (and even amazed) by the length and detail of the column names in this data set. They make the purpose of each column clear... but they're rather long and annoying to use in queries. For this task, I thus asked you to rename the columns to something shorter.

The short and easy way to do this would probably be to define a list of 23 strings, and then assign them to `df.columns`. But why do things the fast and easy way, when we can have some fun? After all, there are a number of patterns that repeat themselves in the column names; perhaps we can exploit that repetition, and let the computer do some of the hard work for us?

It's especially true that there are column names that are identical to one another, save for one or two numbers. Such names would be annoying to identify as specific strings, but with regular expressions, it becomes much easier.

I decided that we could do the following:

- Define a dict in which the keys and values are both strings. The keys will be the regular expressions for which we're searching, and the values will be the string (occasionally including backreferences to the search string) we'll use for replacing. The [re.sub](https://docs.python.org/3/library/re.html?ref=bambooweekly.com#re.sub) method in the [re](https://docs.python.org/3/library/re.html?ref=bambooweekly.com) module (for regular expressions) is just what we want.
- However, that's only good for replacing one string. We'll want to replace each key-value pair from our replacements dict. For that, we'll use a `for` loop, using the `dict.items` method to get each key-value pair in turn.
- Finally, we can use [df.rename](https://www.bambooweekly.com/pandas-rename/) to rename the columns of our data frame. `df.rename` returns a new data frame with the new columns; we'll assign the result back to `df` in each iteration. `df.rename` accepts a `lambda` expression (i.e., a function), which we'll use to apply `re.sub` to each column in the data frame.

In other words, we'll create a dict of replacement text, iterate over that dict, and use `df.rename` along with `re.sub` to perform some substitutions.

You undoubtedly had your own substitutions; here are the ones that I came up with:

```python
import re

replacements = {
    'temperatrures': 'temperatures',
    'population exposed to at least': 'pop >=',
    'number of days of temperatures': 'days',
    r'reaching Climate Shift Index level (\d).*$': r'CS\1',
    'of temperatures at or above the 90th percentile': '>= 90 pct',
    'historical ranking.*': 'historical ranking',
    'mean temperature anomaly.*': 'mean anomaly',
    'days at or above the 90th percentile temperature.*$': 'days >= 90 pct',
    r'number of \*additional\* days.*$': 'additional days >= 90 pct',
    r'\s+': ' '
}

for key, value in replacements.items():
    df = df.rename(columns=lambda colname_: re.sub(key, value, colname_))

```

In one case, I used capturing to identify a digit – `(\d)` – and then refer to it in the replacement string, `'CS\1'`. In a few, I used `.*` to indicate that I wanted to grab the text until the end of the line, which I made even clearer by anchoring it there with `$`. Wherever I had backslashes in my regexp string, I used a raw Python string (i.e., a string with `r` before the leading quote) to automatically double all backslashes, avoiding Python's confusion or warnings for backslashed characters.

I also fixed their misspelled version of "temperatures", and combined multiple whitespace characters into a single space. Note that because a dict retains its order, we can know that the whitespace compression regexp will be the final replacement executed, so it can clean up any words we separated with too much whitespace.

After renaming the columns, they are:

```python
Index(['historical ranking', 'mean anomaly', 'days CS2', 'days CS3',
       'days CS5', 'pop >= 60 days of temperatures CS5', 'days >= 90 pct',
       'additional days >= 90 pct', 'pop >= 1 day >= 90 pct',
       'pop >= 7 days >= 90 pct', 'pop >= 30 days >= 90 pct',
       'pop >= 61 days >= 90 pct', 'pop >= 1 day of temperatures CS2',
       'pop >= 1 day >= 90 pct AND CS2', 'pop >= 7 days >= 90 pct AND CS2',
       'pop >= 30 days >= 90 pct AND CS2', 'pop >= 61 days >= 90 pct AND CS2',
       'pop >= 1 day >= 90 pct AND CS3', 'pop >= 7 days >= 90 pct AND CS3',
       'pop >= 30 days >= 90 pct AND CS3', 'pop >= 61 days >= 90 pct AND CS3',
       'population', 'ISO3'],
      dtype='object')
```

This might be a bit *too* terse, and you undoubtedly did it differently, but the technique is useful.

### How many countries experienced, in June-August 2024, their highest-ever temperatures? Display a pie chart showing the continents where those countries are located. Does such a pie chart really show the relative impact of climate change on each continent? What was the mean temperature anomaly in each continent?

The `historical ranking` column indicated where, historically, this summer's temperatures ranked relative to all other June-August temperatures. In other words, if `historical_ranking` is 1, then this summer marked the record-high temperature for that place.

I first grabbed all of the countries with a `historical_ranking` equal to 1 with [loc](https://www.bambooweekly.com/pandas-loc/) and `lambda`:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
)
```

Next, I was only interested in `historical_ranking`, so I kept just that series:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    ['historical ranking']
)
```

Finally, I invoked [count](https://www.bambooweekly.com/pandas-count/) , which returns the number of non-NaN values in a series:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    ['historical ranking']
    .count()
)
```

The result was 72 – meaning that in 72 countries, this summer marked the highest-ever recorded temperature. Wow.

Next, I asked you to count the number of such countries per continent, and to display the result in a pie chart. Any time we have a "count per" task, it'll almost certainly require the use of [groupby](https://www.bambooweekly.com/pandas-groupby/). You might think that we cannot invoke `groupby` on a column that has been made part of the index – but actually, that's not the case. We can thus say:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    .groupby('continent')['historical ranking'].count()
)
```

In other words, after keeping only those rows of `df` in which `historical_ranking` is 1, we then ask to run `count` for each distinct value in `continent`. We count on the `historical_ranking` column, but we could actually use any column without `NaN` values in it. The result:

```
continent
Africa           11
Asia             21
Europe           12
North America    18
Oceania           8
South America     2
Name: historical ranking, dtype: int64
```

However, I didn't ask for the numeric count. Rather, I wanted to see, in a pie chart, the breakdown, by continent, of hottest-ever-in-2024 countries. I did that by calling `plot.pie` on the series:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    .groupby('continent')['historical ranking'].count()
    .plot.pie()
)
```

The result certainly looked attractive:

![](https://storage.ghost.io/c/06/ba/06ba0cc0-be6f-4de7-af2f-5c20165279b9/content/images/2024/10/image-6.png)

But is this a meaningful plot? Not really; we can see that more countries in North America had super-hot June-July-August periods in 2024 than in South America or Oceania. But is that because there are more countries in North America? Maybe, as we can see from running:

```python
df.groupby('continent')['historical ranking'].count()

```

This gives us:

```python
continent
Africa           54
Asia             50
Europe           43
North America    36
Oceania          22
South America    13
Name: historical ranking, dtype: int64
```

So even if all of South America and Oceania had scorching-hot June-July-August 2024 (which is unlikely, given that it's winter in many of those countries), they still would have smaller pie slices than North America. Pie plots are great, but you have to know when and how to apply them, or you might end up misleading yourself or others. In this case, it might be interesting to know how many countries in each continent had very hot summers, rather than how many out of the total. We could thus use a bar plot:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    .groupby('continent')['historical ranking'].count()
    .plot.bar()
)
```

The result:

![](https://storage.ghost.io/c/06/ba/06ba0cc0-be6f-4de7-af2f-5c20165279b9/content/images/2024/10/image-7.png)

We see the same data here, but it's presented in a way that doesn't lead us to believe that one is growing at the expense of another, or that they can somehow be added up to a grand total.

Finally, I asked you to find the mean temperature anomaly per continent, for those countries that just had their hottest-ever summers:

```python
(
    df
    .loc[lambda df_: df_['historical ranking'] == 1]
    .groupby('continent')['mean anomaly'].mean()
)
```

Once again, we're only interested in those countries that had the hottest-ever period in June-July-August. We then use `groupby` on `continent`, getting the `mean` for `mean anomaly` for each of the continents. The result:

```
continent
Africa           1.183636
Asia             1.453810
Europe           2.670000
North America    0.986667
Oceania          0.726250
South America    1.190000
Name: mean anomaly, dtype: float64
```

In other words, European countries had a much hotter summer on average, than people in other countries – about twice as hot as Asia, and a little more than twice as hot as Africa and South America.

No matter how you slice it, though, we see that temperatures have risen quite a lot.

### How many people were exposed to at least 61 days above the 90th percentile, for each of CS2 and CS3?

We have a column for each of these measures; in order to answer this question, we need to sum each of them. The easiest way to do that is to retrieve the two columns, and then invoke `sum` on them. When we run `sum` on a series, we get a scalar value, the sum of the series. When we run `sum` on a data frame, we get a series back, with the sum of each column.

The trickiest part here is to use double square brackets in order to retrieve two columns:

```python
(
    df
    [['pop >= 61 days >= 90 pct AND CS2', 
      'pop >= 61 days >= 90 pct AND CS3']] 
    .sum()
)
```

The result:

```
pop >= 61 days >= 90 pct AND CS2    453860000
pop >= 61 days >= 90 pct AND CS3    332589000
dtype: int64
```

In other words, 453,860,000 people had more than 61 days in June, July, and August with fairly high temperatures. And 332,589,000 people had more than 61 days with even higher temperatures.

### What were the mean and standard deviations for the "mean anomaly" temperature across all locations in the "Caribbean" region?

To find these values, we first need to retrieve all of the rows in which the region is `'Caribbean'`. If the data frame's index solely contained the region, then that would be fairly easy; we could use `loc`. But we have a multi-index, and we're looking to match only one part of it.

This is where [xs](https://www.bambooweekly.com/pandas-xs/) comes into play, letting us retrieve from any part of a multi-index. In this case, we can say:

```python
(
    df
    .xs('Caribbean', level='region')
)
```

In other words: We want rows where the `region` part of the multi-index is equal to `'Caribbean'`. We can then retrieve the `mean anomaly` column, and calculate (using [agg](https://www.bambooweekly.com/pandas-agg/)) both the mean and standard deviation:

```python
(
    df
    .xs('Caribbean', level='region')
    ['mean anomaly']
    .agg(['mean', 'std'])
)
```

The result:

```
mean    0.951600
std     0.158842
Name: mean anomaly, dtype: float64
```

### What were the mean and standard deviations for the "mean anomaly" temperature across all locations in the "Caribbean" and "Polynesia" regions?

On the face of it, this is a slight variation on the previous question. But sadly, we can't use `xs` to retrieve rows whose `region` is one of these two values. Rather, we'll need to use [pd.IndexSlice](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IndexSlice.html?ref=bambooweekly.com), an object designed to let us retrieve from various parts of multi-indexes.

`pd.IndexSlice` works like a method, but it (like `loc`) is an object that uses square brackets, giving it a bit more flexibility with Python's syntax. When we invoke `pd.IndexSlice`, we pass a number of arguments. Each can be a Python `slice` object, or it can be a list of values that should serve as a match:

- We want to allow for any continent, so we'll pass `slice(None)`. Or, because we're in square brackets, we can just use `:`, meaning "from the start to the end" in slice-speak.
- We want either `'Caribbean'` or `'Polynesia'` to match, so we pass a list of those values.
- Finally, we want to allow for any country, so we once again pass either `slice(None)` or the syntactic sugar we're more familiar with, `:`.

The final query is:

```python
(
    df
    .loc[pd.IndexSlice[:, ['Caribbean', 'Polynesia'], :]]
    ['mean anomaly']
    .agg(['mean', 'std'])
)
```

The result:

```
mean    0.786970
std     0.337967
Name: mean anomaly, dtype: float64
```

### How many days, on average, did G7 countries (Canada, France, Germany, Italy, Japan, United Kingdom, and the United States) experience a Climate Shift Index of 3 or higher?

Finally, let's find out the number of days that G7 countries had CSI 3 or higher. We'll once again use a `pd.IndexSlice` object, this time giving a list of values for the `country` portion of our multi-index:

```python
(
    df
    .loc[pd.IndexSlice[slice(None), slice(None), 
        ['Canada', 'France', 'Germany', 
         'Italy', 'Japan', 'United Kingdom',
         'United States of America']],
        'days CS3']
)
```

Notice that we're using the two-argument version of `loc` here, with the `pd.IndexSlice` call providing the row selector, and `days CS3` acting as the column selector. We get back:

```
continent      region            country/territory/dependency
North America  Northern America  Canada                           3.29
Europe         Western Europe    France                          13.41
                                 Germany                          5.33
               Southern Europe   Italy                           48.01
Asia           Eastern Asia      Japan                           42.76
Europe         Northern Europe   United Kingdom                   6.96
North America  Northern America  United States of America        12.71
Name: days CS3, dtype: float64
```

But we want the mean of all the values:

```python
(
    df
    .loc[pd.IndexSlice[slice(None), slice(None), 
        ['Canada', 'France', 'Germany', 
         'Italy', 'Japan', 'United Kingdom',
         'United States of America']],
        'days CS3']
    .mean()
)
```

And the result ends up being about 18.92\. Which is, we can probably agree, still a lot of hot days.

I hope that you enjoyed this week's questions! You can download my Jupyter notebook from here: [https://drive.google.com/file/d/1RG\_23XgWuIwZzAR6g33C2UwwKWCfk-hm/view?usp=sharing](https://drive.google.com/file/d/1RG%5F23XgWuIwZzAR6g33C2UwwKWCfk-hm/view?usp=sharing&ref=bambooweekly.com)

I'll be back next week with more data-analysis questions with Pandas.

Reuven