Puzzle 23 Chain of Commands
Pandas Brain Teasers — by Miki Tebeka (31 / 34)
Published in
3 min readMar 23, 2022
👈 Find Me a Phone Booth | TOC | Late Addition 👉
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.
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>
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…