Puzzle 23 Chain of Commands

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Find Me a Phone Booth | TOC | Late Addition 👉

by_ip.py

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

​ df = pd.DataFrame([
​ [​'133.43.96.45'​, pd.Timedelta(​'3s'​)],
​ [​'133.68.18.180'​, pd.Timedelta(​'2s'​)],
​ [​'133.43.96.45'​, pd.NaT],
​ [​'133.43.96.45'​, pd.Timedelta(​'4s'​)],
​ [​'133.43.96.45'​, pd.Timedelta(​'2s'​)],
​ ], columns=[​'ip'​, ​'duration'​])

​ by_ip = (
​ df[​'duration'​]
​ .fillna(pd.Timedelta(seconds=1))
​ .groupby(df[​'ip'​])
​ .sum()
​ )
​ ​print​(by_ip)

Guess the Output

IMPORTANT

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

images/hline.png

This code will print:

​ ip
​ 133.43.96.45 00:00:10
​ 133.68.18.180 00:00:02
​ Name: duration, dtype: timedelta64[ns]</code></pre></td>
images/hline.png

The surprising fact here is that it’s valid Python code.

Python’s use of white space is pretty unique in programming languages. Some people don’t like it. I find it makes the…

--

--

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.