Skip to content

Instantly share code, notes, and snippets.

View mh0w's full-sized avatar
💭
🦆

Matthew Hawkes_ONS mh0w

💭
🦆
View GitHub Profile
@mh0w
mh0w / Get script's directory.py
Created October 21, 2022 14:39
Get script's directory
import os
print(os.path.dirname(os.path.realpath(__file__)))
@mh0w
mh0w / detect python version inside python kernel.py
Created October 21, 2022 14:42
detect python version inside python kernel
import sys
sys.version_info
@mh0w
mh0w / check object size.py
Last active January 10, 2024 17:31
check object size
"""
sys:
Return the size of an object in bytes.The object can be any type of object.
All built-in objects will return correct results, but this does not have to
hold true for third-party extensions as it is implementation specific.
pandas/polars:
Returns the size of an object in KB/MB/GB. Checking the dtypes will be
informative (e.g., float64 likely to use more space than int8).
"""
@mh0w
mh0w / check if file exists.py
Created October 21, 2022 14:50
check if file exists
import os
os.path.exists('xxx.txt')
@mh0w
mh0w / get the class name of an object.py
Created October 21, 2022 15:03
get the class name of an object
a = "x"
b = 1
c = 1.2
print(a.__class__.__name__) # str
print(b.__class__.__name__) # int
print(c.__class__.__name__) # float
@mh0w
mh0w / check if a variable exists.py
Created October 21, 2022 15:08
check if a variable exists
a = 1
'a' in locals() # True
'z' in locals() # False
'a' in globals() # True
'z' in globals() # False
@mh0w
mh0w / lists: create, remove, clear.py
Created October 21, 2022 15:12
lists: create, isolate, remove, clear
mylist = ['a', 'b', 'c', 'd']
# Remove item 1
mylist.pop(1) #'b'
print(l) #['a', 'c', 'd']
# Remove item with value 'd'
mylist.remove('d')
print(l) # ['a', 'c']
@mh0w
mh0w / get N largest values from a list.py
Created October 21, 2022 15:21
get N largest values from a list
import heapq
print(heapq.nlargest(3, [10, 5, 3, 8, 4, 2])) # [10, 8, 5]
@mh0w
mh0w / convert two list to a list of tuples.py
Created October 21, 2022 15:23
convert two list to a list of tuples
l1 = [1,2,3]
l2 = [4,5,6]
print(list(zip(l1, l2))) #[(1, 4), (2, 5), (3, 6)]
@mh0w
mh0w / convert list of tuples to two lists.py
Created October 21, 2022 15:25
convert list of tuples to two lists
z = zip(*[(1, 2), (3, 4), (5, 6)])
l1, l2 = map(list, z)
print(l1) #[1, 3, 5]
print(l2) #[2, 4, 6]