Puzzle 14 A Tale of One City

Pandas Brain Teasers — by Miki Tebeka (22 / 34)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 A 10% Discount | TOC | Free-Range 👉

population.py

​ ​import​ ​pandas​ ​as​ ​pd​

​ cities = pd.DataFrame([
​ (​'Vienna'​, ​'Austria'​, 1_899_055),
​ (​'Sofia'​, ​'Bulgaria'​, 1_238_438),
​ (​'Tekirdağ'​, ​'Turkey'​, 1_055_412),
​ ], columns=[​'City'​, ​'Country'​, ​'Population'​])


​ ​def​ ​population_of​(city):
​ ​return​ cities[cities[​'City'​] == city][​'Population'​]


​ city = ​'Tekirdağ'​
​ ​print​(population_of(city))

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print: Series([], Name: Population, dtype: int64)

images/hline.png

The output means we can’t find Tekirdağ in the cities DataFrame. But … it’s right there!

Let’s investigate:

​ In [1]: city
​ Out[1]: ​'Tekirdağ'​
​ In [2]: city2 = cities.loc[2][​'City'​]
​ In [3]: city2
​ Out[3]: ​'Tekirdağ'​
​ In [4]: city2 == city
​ Out[4]: False

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.