Puzzle 15 Free-Range

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 A Tale of One City | TOC | Y3K 👉

loc.py

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

​ df = pd.DataFrame([
​ [1, 1, 1],
​ [2, 2, 2],
​ [3, 3, 3],
​ [4, 4, 4],
​ [5, 5, 5],

​ ])

​ ​print​(len(df.loc[1:3]))

Guess the Output

IMPORTANT

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

images/hline.png

This code will print: 3

images/hline.png

Slices in Python are half-open ranges. You get values from the first index, up to but not including the last index:

​ In [1]: chars = [​'a'​, ​'b'​, ​'c'​, ​'d'​, ​'e'​]
​ In [2]: chars[1:3]
​ Out[2]: [​'b'​, ​'c'​]

And most of the time, Pandas words the same way:

​ In [3]: s = pd.Series(chars)
​ In [4]: s[1:3]
​ Out[4]:
​ 1 b
​ 2 c
​ dtype: object

There are three ways to slice a pandas.Series or a pandas.DataFrame:

  • Using loc, which works by label
  • Using iloc, which works by offset

--

--

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.