10000 Datetime, Duck types, Pandas · gto76/python-cheatsheet@cd34692 · GitHub
[go: up one dir, main page]

Skip to content

Commit cd34692

Browse files
committed
Datetime, Duck types, Pandas
1 parent d252dfe commit cd34692

File tree

2 files changed

+22
-22
lines changed

2 files changed

+22
-22
lines changed

README.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,7 @@ import zoneinfo, dateutil.tz
603603
<DT> = datetime(year, month, day, hour=0) # Also: `minute=0, second=0, microsecond=0, …`.
604604
<TD> = timedelta(weeks=0, days=0, hours=0) # Also: `minutes=0, seconds=0, microseconds=0`.
605605
```
606-
* **Aware times and datetimes have defined timezone, while naive don't. If object is naive, it is presumed to be in the system's timezone!**
606+
* **Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!**
607607
* **`'fold=1'` means the second pass in case of time jumping back for one hour.**
608608
* **Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns `'[±D, ]H:MM:SS[.…]'` and total_seconds() a float of all seconds.**
609609
* **Use `'<D/DT>.weekday()'` to get the day of the week as an int, with Monday being 0.**
@@ -1155,7 +1155,8 @@ class MySortable:
11551155
### Iterator
11561156
* **Any object that has methods next() and iter() is an iterator.**
11571157
* **Next() should return next item or raise StopIteration exception.**
1158-
* **Iter() should return 'self', i.e. unmodified object on which it was called.**
1158+
* **Iter() should return an iterator of remaining items, i.e. 'self'.**
1159+
* **Only objects that have iter() method can be used in for loops.**
11591160
```python
11601161
class Counter:
11611162
def __init__(self):
@@ -1181,7 +1182,7 @@ class Counter:
11811182

11821183
### Callable
11831184
* **All functions and classes have a call() method, hence are callable.**
1184-
* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable. Calling an uncallable object raises `'TypeError'`.**
1185+
* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable. Calling an uncallable object raises TypeError.**
11851186
* **When this cheatsheet uses `'<function>'` as an argument, it means `'<callable>'`.**
11861187
```python
11871188
class Counter:
@@ -1727,8 +1728,8 @@ os.remove(<path>) # Deletes the file.
17271728
os.rmdir(<path>) # Deletes the empty directory.
17281729
shutil.rmtree(<path>) # Deletes the directory.
17291730
```
1730-
* **Paths can be either strings, Paths, or DirEntry objects.**
1731-
* **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).**
1731+
* **Paths can be either strings, Path objects, or DirEntry objects.**
1732+
* **Functions report OS related errors by raising OSError or one of its [subclasses](#exceptions-1).**
17321733

17331734
### Shell Commands
17341735
```python
@@ -2257,7 +2258,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
22572258
<Thread>.join() # Waits for the thread to finish executing.
22582259
```
22592260
* **Use `'kwargs=<dict>'` to pass keyword arguments to the function.**
2260-
* **Use `'daemon=True'`, or the program will not be able to exit while the thread is alive.**
2261+
* **Use `'daemon=True'`, or program won't be able to exit while the thread is alive.**
22612262

22622263
### Lock
22632264
```python
@@ -3185,9 +3186,10 @@ Name: a, dtype: int64
31853186
<S>.plot.line/area/bar/pie/hist() # Generates a plot. `plt.show()` displays it.
31863187
```
31873188
* **Use `'print(<S>.to_string())'` to print a Series that has more than 60 items.**
3188-
* **Indexing objects can't be tuples because `'obj[x, y]'` is converted to `'obj[(x, y)]'`.**
3189+
* **Use `'<S>.index'` to get collection of keys and `'<S>.index = <coll>'` to update them.**
3190+
* **Only pass a list or Series to loc/iloc because `'obj[x, y]'` is converted to `'obj[(x, y)]'` and `'<S>.loc[key_1, key_2]'` is how you retrieve a value from a multi-indexed Series.**
31893191
* **Pandas uses NumPy types like `'np.int64'`. Series is converted to `'float64'` if we assign np.nan to any item. Use `'<S>.astype(<str/type>)'` to get converted Series.**
3190-
* **Series will silently overflow if we run `'pd.Series([100], dtype="int8") + 100'`!**
3192+
* **Series will silently overflow if you run `'pd.Series([100], dtype="int8") + 100'`!**
31913193

31923194
#### Series — Aggregate, Transform, Map:
31933195
```python
@@ -3214,7 +3216,6 @@ Name: a, dtype: int64
32143216
| | y 2.0 | y 2.0 | y 2.0 |
32153217
+--------------+-------------+-------------+---------------+
32163218
```
3217-
* **Last result has a multi-index. Use `'<S>[key_1, key_2]'` to get its values.**
32183219

32193220
### DataFrame
32203221
**Table with labeled rows and columns.**

index.html

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656

5757
<body>
5858
<header>
59-
<aside>April 27, 2025</aside>
59+
<aside>April 30, 2025</aside>
6060
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
6161
</header>
6262

@@ -536,7 +536,7 @@
536536
&lt;TD&gt; = timedelta(weeks=<span class="hljs-number">0</span>, days=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>) <span class="hljs-comment"># Also: `minutes=0, seconds=0, microseconds=0`.</span>
537537
</code></pre>
538538
<ul>
539-
<li><strong>Aware times and datetimes have defined timezone, while naive don't. If object is naive, it is presumed to be in the system's timezone!</strong></li>
539+
<li><strong>Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!</strong></li>
540540
<li><strong><code class="python hljs"><span class="hljs-string">'fold=1'</span></code> means the second pass in case of time jumping back for one hour.</strong></li>
541541
<li><strong>Timedelta normalizes arguments to ±days, seconds (&lt; 86 400) and microseconds (&lt; 1M). Its str() method returns <code class="python hljs"><span class="hljs-string">'[±D, ]H:MM:SS[.…]'</span></code> and total_seconds() a float of all seconds.</strong></li>
542542
<li><strong>Use <code class="python hljs"><span class="hljs-string">'&lt;D/DT&gt;.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
@@ -988,7 +988,8 @@
988988
<div><h3 id="iterator-1">Iterator</h3><ul>
989989
<li><strong>Any object that has methods next() and iter() is an iterator.</strong></li>
990990
<li><strong>Next() should return next item or raise StopIteration exception.</strong></li>
991-
<li><strong>Iter 10000 () should return 'self', i.e. unmodified object on which it was called.</strong></li>
991+
<li><strong>Iter() should return an iterator of remaining items, i.e. 'self'.</strong></li>
992+
<li><strong>Only objects that have iter() method can be used in for loops.</strong></li>
992993
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
993994
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
994995
self.i = <span class="hljs-number">0</span>
@@ -1011,7 +1012,7 @@
10111012
<li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li>
10121013
</ul><div><h3 id="callable">Callable</h3><ul>
10131014
<li><strong>All functions and classes have a call() method, hence are callable.</strong></li>
1014-
<li><strong>Use <code class="python hljs"><span class="hljs-string">'callable(&lt;obj&gt;)'</span></code> or <code class="python hljs"><span class="hljs-string">'isinstance(&lt;obj&gt;, collections.abc.Callable)'</span></code> to check if object is callable. Calling an uncallable object raises <code class="python hljs"><span class="hljs-string">'TypeError'</span></code>.</strong></li>
1015+
<li><strong>Use <code class="python hljs"><span class="hljs-string">'callable(&lt;obj&gt;)'</span></code> or <code class="python hljs"><span class="hljs-string">'isinstance(&lt;obj&gt;, collections.abc.Callable)'</span></code> to check if object is callable. Calling an uncallable object raises TypeError.</strong></li>
10151016
<li><strong>When this cheatsheet uses <code class="python hljs"><span class="hljs-string">'&lt;function&gt;'</span></code> as an argument, it means <code class="python hljs"><span class="hljs-string">'&lt;callable&gt;'</span></code>.</strong></li>
10161017
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
10171018
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
@@ -1460,8 +1461,8 @@
14601461
shutil.rmtree(&lt;path&gt;) <span class="hljs-comment"># Deletes the directory.</span>
14611462
</code></pre>
14621463
<ul>
1463-
<li><strong>Paths can be either strings, Paths, or DirEntry objects.</strong></li>
1464-
<li><strong>Functions report OS related errors by raising either OSError or one of its <a href="#exceptions-1">subclasses</a>.</strong></li>
1464+
<li><strong>Paths can be either strings, Path objects, or DirEntry objects.</strong></li>
1465+
<li><strong>Functions report OS related errors by raising OSError or one of its <a href="#exceptions-1">subclasses</a>.</strong></li>
14651466
</ul>
14661467
<div><h3 id="shellcommands">Shell Commands</h3><pre><code class="python language-python hljs">&lt;pipe&gt; = os.popen(<span class="hljs-string">'&lt;commands&gt;'</span>) <span class="hljs-comment"># Executes commands in sh/cmd. Returns combined stdout.</span>
14671468
&lt;str&gt; = &lt;pipe&gt;.read(size=<span class="hljs-number">-1</span>) <span class="hljs-comment"># Reads 'size' chars or until EOF. Also readline/s().</span>
@@ -1865,7 +1866,7 @@ <h3 id="format-2">Format</h3><div><h4 id="forstandardtypesizesandmanualalignment
18651866

18661867
<ul>
18671868
<li><strong>Use <code class="python hljs"><span class="hljs-string">'kwargs=&lt;dict&gt;'</span></code> to pass keyword arguments to the function.</strong></li>
1868-
<li><strong>Use <code class="python hljs"><span class="hljs-string">'daemon=True'</span></code>, or the program will not be able to exit while the thread is alive.</strong></li>
1869+
<li><strong>Use <code class="python hljs"><span class="hljs-string">'daemon=True'</span></code>, or program won't be able to exit while the thread is alive.</strong></li>
18691870
</ul>
18701871
<div><h3 id="lock">Lock</h3><pre><code class="python language-python hljs">&lt;lock&gt; = Lock/RLock() <span class="hljs-comment"># RLock can only be released by acquirer.</span>
18711872
&lt;lock&gt;.acquire() <span class="hljs-comment"># Waits for the lock to be available.</span>
@@ -2612,9 +2613,10 @@ <h3 id="format-2">Format</h3><div><h4 id="forstandardtypesizesandmanualalignment
26122613
</code></pre>
26132614
<ul>
26142615
<li><strong>Use <code class="python hljs"><span class="hljs-string">'print(&lt;S&gt;.to_string())'</span></code> to print a Series that has more than 60 items.</strong></li>
2615-
<li><strong>Indexing objects can't be tuples because <code class="python hljs"><span class="hljs-string">'obj[x, y]'</span></code> is converted to <code class="python hljs"><span class="hljs-string">'obj[(x, y)]'</span></code>.</strong></li>
2616+
<li><strong>Use <code class="python hljs"><span class="hljs-string">'&lt;S&gt;.index'</span></code> to get collection of keys and <code class="python hljs"><span class="hljs-string">'&lt;S&gt;.index = &lt;coll&gt;'</span></code> to update them.</strong></li>
2617+
<li><strong>Only pass a list or Series to loc/iloc because <code class="python hljs"><span class="hljs-string">'obj[x, y]'</span></code> is converted to <code class="python hljs"><span class="hljs-string">'obj[(x, y)]'</span></code> and <code class="python hljs"><span class="hljs-string">'&lt;S&gt;.loc[key_1, key_2]'</span></code> is how you retrieve a value from a multi-indexed Series.</strong></li>
26162618
<li><strong>Pandas uses NumPy types like <code class="python hljs"><span class="hljs-string">'np.int64'</span></code>. Series is converted to <code class="python hljs"><span class="hljs-string">'float64'</span></code> if we assign np.nan to any item. Use <code class="python hljs"><span class="hljs-string">'&lt;S&gt;.astype(&lt;str/type&gt;)'</span></code> to get converted Series.</strong></li>
2617-
<li><strong>Series will silently overflow if we run <code class="python hljs"><span class="hljs-string">'pd.Series([100], dtype="int8") + 100'</span></code>!</strong></li>
2619+
<li><strong>Series will silently overflow if you run <code class="python hljs"><span class="hljs-string">'pd.Series([100], dtype="int8") + 100'</span></code>!</strong></li>
26182620
</ul>
26192621
<div><h4 id="seriesaggregatetransformmap">Series — Aggregate, Transform, Map:</h4><pre><code class="python language-python hljs">&lt;el&gt; = &lt;S&gt;.sum/max/mean/std/idxmax/count() <span class="hljs-comment"># Or: &lt;S&gt;.agg(lambda &lt;S&gt;: &lt;el&gt;)</span>
26202622
&lt;S&gt; = &lt;S&gt;.rank/diff/cumsum/ffill/interpol…() <span class="hljs-comment"># Or: &lt;S&gt;.agg/transform(lambda &lt;S&gt;: &lt;S&gt;)</span>
@@ -2637,9 +2639,6 @@ <h3 id="format-2">Format</h3><div><h4 id="forstandardtypesizesandmanualalignment
26372639
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
26382640
</code></pre>
26392641

2640-
<ul>
2641-
<li><strong>Last result has a multi-index. Use <code class="python hljs"><span class="hljs-string">'&lt;S&gt;[key_1, key_2]'</span></code> to get its values.</strong></li>
2642-
</ul>
26432642
<div><h3 id="dataframe">DataFrame</h3><p><strong>Table with labeled rows and columns.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>df = pd.DataFrame([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]], index=[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], columns=[<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>]); df
26442643
x y
26452644
a <span class="hljs-number">1</span> <span class="hljs-number">2</span>
@@ -2942,7 +2941,7 @@ <h3 id="format-2">Format</h3><div><h4 id="forstandardtypesizesandmanualalignment
29422941

29432942

29442943
<footer>
2945-
<aside>April 27, 2025</aside>
2944+
<aside>April 30, 2025</aside>
29462945
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
29472946
</footer>
29482947

0 commit comments

Comments
 (0)
0