Skip to content

Commit b8f5ae2

Browse files
committed
Merge branch 'main' into 23-add-note-on-getting-index-from-name
2 parents 32a5c6a + e8ab4fb commit b8f5ae2

3 files changed

Lines changed: 40 additions & 40 deletions

File tree

episodes/02-dictionaries.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,7 @@ This package provides the method `json.load()` to read JSON data from a file and
350350
```python
351351
import json
352352

353-
with open('ro-crate-metadata-1.json') as f:
353+
with open('data/ro-crate-metadata-1.json') as f:
354354
data = json.load(f)
355355
```
356356

episodes/06-units_and_quantities.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ u.rad.find_equivalent_units()
295295
We can see from this that the degree unit is `u.deg`, so we can use this to define our angles:
296296

297297
```python
298-
angle = 90 * u.deg()
298+
angle = 90 * u.deg
299299
print('angle in degrees: {}; and in radians: {}'.format(angle.value,angle.to(u.rad).value))
300300
```
301301

episodes/07-pandas_essential.md

Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,15 @@ with a text editor and look at the data layout.
4141
The data within this file is organised much as you'd expect the data within a spreadsheet. The first row of the file contains the headers for each of the columns. The first column contains the name of the countries, while the remaining columns contain the GDP values for these countries for each year. Pandas has the `read_csv` function for reading structured data such as this, which makes reading the file easy:
4242

4343
```python
44-
data = pd.read_csv('data/gapminder_gdp_europe.csv',index_col='country')
44+
df = pd.read_csv('data/gapminder_gdp_europe.csv',index_col='country')
4545
```
4646

4747
Here we specify that the `country` column should be used as the index column (`index_col`).
4848

4949
This creates a `DataFrame` object containing the dataset. This is similar to a numpy array, but has a number of significant differences. The first is that there are more ways to quickly understand a pandas dataframe. For example, the `info` function gives an overview of the data types and layout of the DataFrame:
5050

5151
```python
52-
data.info()
52+
df.info()
5353
```
5454

5555
```output
@@ -74,10 +74,10 @@ dtypes: float64(12)
7474
memory usage: 3.0+ KB
7575
```
7676

77-
You can also carry out quick analysis of the data using the `describe` function:
77+
You can also carry out quick analysis of the DataFrame using the `describe` function:
7878

7979
```python
80-
data.describe()
80+
df.describe()
8181
```
8282

8383
```output
@@ -94,60 +94,60 @@ max 14734.232750 17909.489730 20431.092700 ...
9494

9595
## Accessing elements, rows, and columns
9696

97-
The other major difference to numpy arrays is that we cannot directly access the array elements using numerical indices such as `data[0,0]`. It is possible to access columns of data using the column headers as indices (for example, `data['gdpPercap_1952']`), but this is not recommended. Instead you should use the `iloc` and `loc` methods.
97+
The other major difference to numpy arrays is that we cannot directly access the array elements using numerical indices such as `df[0,0]`. It is possible to access columns of data using the column headers as indices (for example, `df['gdpPercap_1952']`), but this is not recommended. Instead you should use the `iloc` and `loc` methods.
9898

9999
The `iloc` method enables us to access the DataFrame as we would a numpy array:
100100

101101
```python
102-
print(data.iloc[0,0])
102+
print(df.iloc[0,0])
103103
```
104104

105105
while the `loc` method enables the same access using the index and column headers:
106106

107107
```python
108-
print(data.loc["Albania", "gdpPercap_1952"])
108+
print(df.loc["Albania", "gdpPercap_1952"])
109109
```
110110

111111
For both of these methods, we can leave out the column indexes, and these will all be returned for the specified index row:
112112

113113
```python
114-
print(data.loc["Albania"])
114+
print(df.loc["Albania"])
115115
```
116116

117-
This will not work for column headings (in the inverse of the `data['gdpPercap_1952']` method) however. While it is quick to type, we recommend trying to avoid using this method of slicing the DataFrame, in favour of the methods described below.
117+
This will not work for column headings (in the inverse of the `df['gdpPercap_1952']` method) however. While it is quick to type, we recommend trying to avoid using this method of slicing the DataFrame, in favour of the methods described below.
118118

119119
For both of these methods we can use the `:` character to select all elements in a row or column. For example, to get all information for Albania:
120120

121121
```python
122-
print(data.loc["Albania", :])
122+
print(df.loc["Albania", :])
123123
```
124124

125125
or:
126126

127127
```python
128-
print(data.iloc[0, :])
128+
print(df.iloc[0, :])
129129
```
130130

131131
Note that here we knew that Albania was the first country in the DataFrame, so we were able to ask for the first column (0). If you needed to know the column ID for a particular country, you could do this using `get_loc()`, e.g. `data.index.get_loc("France")` should tell you the column ID value for France.
132132

133133
The `:` character by itself is shorthand to indicate all elements across that index, but it can also be combined with index values or column headers to specify a slice of the DataArray:
134134

135135
```python
136-
print(data.loc["Albania", 'gdpPercap_1962':'gdpPercap_1972'])
136+
print(df.loc["Albania", 'gdpPercap_1962':'gdpPercap_1972'])
137137
```
138138

139139
If either end of the slice definition is omitted, then the slice will run to the end of that index (just as it does for `:` by itself):
140140

141141
```python
142-
print(data.loc["Albania", 'gdpPercap_1962':])
142+
print(df.loc["Albania", 'gdpPercap_1962':])
143143
```
144144

145145
Slices can also be defined using a list of indexes or column headings:
146146

147147
```python
148148
year_list = ['gdpPercap_1952','gdpPercap_1967','gdpPercap_1982','gdpPercap_1997']
149149
country_list = ['Albania','Belgium']
150-
print(data.loc[country_list, year_list])
150+
print(df.loc[country_list, year_list])
151151
```
152152

153153
```output
@@ -159,10 +159,10 @@ Belgium 8343.105127 13149.041190 20979.845890 27561.196630
159159

160160
## Masking data
161161

162-
Pandas data arrays are based on numpy arrays, and retain some of the numpy tools, such as masked arrays. This enables us to apply selection criteria to the datasets, so that only the values that we require are shown. For example, the following selects all data where the GDP is above $10,000:
162+
Pandas Dataframes are based on numpy arrays, and retain some of the numpy tools, such as masked arrays. This enables us to apply selection criteria to the Dataframes, so that only the values that we require are shown. For example, the following selects all data where the GDP is above $10,000:
163163

164164
```python
165-
subset = data.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972']
165+
subset = df.loc['Italy':'Poland', 'gdpPercap_1962':'gdpPercap_1972']
166166
print(subset[subset>10000])
167167
```
168168

@@ -181,7 +181,7 @@ Poland NaN NaN NaN
181181
Pandas is integrated with matplotlib, and so data can be plotted directly using the integrated `plot` method. For example, to plot the GDP for Sweden:
182182

183183
```python
184-
data.loc['Sweden',:].plot()
184+
df.loc['Sweden',:].plot()
185185
plt.xticks(rotation=90)
186186
```
187187

@@ -193,7 +193,7 @@ Note that, in the case above, we passed a single column of data to the `plot` me
193193
For example, we will transpose the GDP data for the first 3 countries in our dataset:
194194

195195
```python
196-
print(data.iloc[0:3,:].T)
196+
print(df.iloc[0:3,:].T)
197197
```
198198

199199
```output
@@ -216,7 +216,7 @@ This data is now ready to be plotted as a histogram - first we set the style of
216216

217217
```python
218218
plt.style.use('ggplot')
219-
data.iloc[0:3,:].T.plot(kind='bar')
219+
df.iloc[0:3,:].T.plot(kind='bar')
220220
plt.xticks(rotation=90)
221221
plt.ylabel('GDP per capita')
222222
```
@@ -239,7 +239,7 @@ axis (`axs`) objects. Pass the axis object to pandas when plotting your figure
239239

240240
```python
241241
fig, axs = plt.subplots()
242-
data.loc['Albania':'Belgium',:].T.plot(kind='bar',ax=axs)
242+
df.loc['Albania':'Belgium',:].T.plot(kind='bar',ax=axs)
243243
plt.xticks(rotation=90)
244244
plt.ylabel('GDP per capita')
245245
fig.savefig('albania-austria-belgium_GDP.png', bbox_inches='tight')
@@ -253,26 +253,26 @@ fig.savefig('albania-austria-belgium_GDP.png', bbox_inches='tight')
253253

254254
Note that the x-tick labels have been taken directly from the index values of the transposed DataFrame (which were the original column labels). These don't really need to be more than the year of the GDP values, so we could change the column labels to reflect this.
255255

256-
First we make a new copy of the dataframe (in case anything goes wrong):
256+
First we make a new copy of the DataFrame (in case anything goes wrong):
257257

258258
```python
259-
gdpPercap = data.copy(deep=True)
259+
df_gdpPercap = df.copy(deep=True)
260260
```
261261

262-
We have given this new dataframe a more appropriate name, replacing the information that will be removed from the column headers.
262+
We have given this new DataFrame a more appropriate name, replacing the information that will be removed from the column headers.
263263

264264
Now we will use the inbuilt `str.strip` method to clean up our column labels for the new
265-
dataframe. Which of these commands is correct:
265+
DataFrame. Which of these commands is correct:
266266

267-
1. `gdpPercap.columns = data.columns.str.strip('gdpPercap_')`
268-
2. `gdpPercap = data.columns.str.strip('gdpPercap_')`
267+
1. `df_gdpPercap.columns = df.columns.str.strip('gdpPercap_')`
268+
2. `df_gdpPercap = df.columns.str.strip('gdpPercap_')`
269269

270270
::::::::::::::: solution
271271

272272
## Solution
273273

274274
The correct answer is 1. We have to pass the new column labels explicitly back to the
275-
array columns, otherwise all we do is replace the data array with a list of the new
275+
array columns, otherwise all we do is replace the DataFrame with a list of the new
276276
column labels.
277277

278278

@@ -289,7 +289,7 @@ Now that we've cleaned up the column labels, we now want to plot the GDP data fo
289289
Sweden and Iceland from 1972 onwards. The code block we will be using is:
290290

291291
```python
292-
gdp_percap<BLOCK>.T.plot(kind='line')
292+
df_gdpPercap<BLOCK>.T.plot(kind='line')
293293

294294
# Create legend.
295295
plt.legend(loc='upper left')
@@ -299,18 +299,18 @@ plt.ylabel('GDP per capita ($)')
299299

300300
Which of the following blocks of code should replace the `<BLOCK>` in the code above?
301301

302-
1. `.loc['Sweden':'Iceland','gdpPercap_1972':]`
303-
2. `.loc['gdpPercap_1972':,['Sweden','Iceland']]`
304-
3. `.loc[['Sweden','Iceland'],'gdpPercap_1972':]`
305-
4. `.loc['gdpPercap_1972':,'Sweden':'Iceland']`
302+
1. `.loc['Sweden':'Iceland','1972':]`
303+
2. `.loc['1972':,['Sweden','Iceland']]`
304+
3. `.loc[['Sweden','Iceland'],'1972':]`
305+
4. `.loc['1972':,'Sweden':'Iceland']`
306306

307307
::::::::::::::: solution
308308

309309
## Solution
310310

311311
The correct answer is 3. The two countries are not adjacent in the dataset, so we need
312312
to use a list to slice them, not a range (disqualifying answers 1 and 4). At the point
313-
where we select the countries using `.loc`, we have not yet transposed the dataset
313+
where we select the countries using `.loc`, we have not yet transposed the DataFrame
314314
(using `.T`), so the country names are still indexes, not column labels, and therefore
315315
need to be referenced first (ie in the first set of square brackets), (disqualifying
316316
answers 2 and 4).
@@ -325,11 +325,11 @@ answers 2 and 4).
325325

326326
:::::::::::::::::::::::::::::::::::::::: keypoints
327327

328-
- CSV data is loaded using the `load_csv()` function
329-
- The `describe()` function gives a quick analysis of the data
330-
- `loc[<index>,<column>]` indexes the data array by the index and column labels
331-
- `iloc[<index>,<column>]` indexes the data array using numerical indicies
332-
- The data can be sliced by providing index and/or column indicies as ranges or lists of values
328+
- CSV data is loaded using the `read_csv()` function to create a pandas `DataFrame` object
329+
- The `describe()` function gives a quick analysis of the DataFrame
330+
- `loc[<index>,<column>]` indexes the DataFrame by the index and column labels
331+
- `iloc[<index>,<column>]` indexes the DataFrame using numerical indices
332+
- The data can be sliced by providing index and/or column indices as ranges or lists of values
333333
- The built-in `plot()` function can be used to plot the data using the `matplotlib` library
334334

335335
::::::::::::::::::::::::::::::::::::::::::::::::::

0 commit comments

Comments
 (0)