Python

tags
Programming languages, Coding

Code tips

Categories to one-hot

This is a handy technique but can be very resource intensive for large arrays.

  import numpy as np
  a = np.random.randrange(5, size=10)
  one_hot_a = np.eye(5)[a]

Side-output for jupyter notebooks

Insert the following block in a notebook cell and execute as code (From Twitter). This will put the output of each cell on the side of the code.

  %%html
  <style>
  #notebook-container {width: 100%; background-color: #EEE}
  .code_cell {flex-direction: row !important;}
  .code_cell .output_wrapper {width: 50%;background-color: #FFF}
  .code_cell .input {width: 50%;background-color: #FFF}
  </style>

Convert the code cell to markdown to cancel.

Dataclasses

Dataclass can be used to automatically generate special methods like __init__() and __repr__() for a python class.

  from dataclasses import dataclass

  @dataclass
  class InventoryItem:
      """Class for keeping track of an item in inventory."""
      name: str
      unit_price: float
      quantity_on_hand: int = 0

      def total_cost(self) -> float:
          return self.unit_price * self.quantity_on_hand

Pathlib

Pathlib is an extremely useful library for manipulating paths. It is less cumbersome than using os.path.join() repeatedly.

  from pathlib import Path
  p = Path('/')
  print("List subdir:", [x for x in p.iterdir() if x.is_dir()])
  q = p / 'init.d' / 'reboot'
  print(q)
  print(q.resolve())
  print(q.exists())
  print(q.is_dir())
  with q.open() as f: f.readline()

← Back to Notes