Skip to content

Instantly share code, notes, and snippets.

View otayeby's full-sized avatar
🏠
Working from home

Omar Eltayeby otayeby

🏠
Working from home
View GitHub Profile
@otayeby
otayeby / gen_contingency_table.py
Last active March 18, 2021 00:48
Generate the contingency table for 2 categorical variables in a Pandas DataFrame
# Install xarray first
# col1 & col2: hold the categorical variables
# col3: a column which has a value in all rows
contingency_table = ((df.groupby(['col1', 'col2']).count().to_xarray()['col3']).values).tolist()
@otayeby
otayeby / passing-last-index.py
Created April 11, 2018 01:10
Using None to index all elements
"""
You have a function that takes an argument, this argument is the index of the last element you want to show from an
array. At some point you want found out that you want to use this function but grab all elements. Just pass None.
"""
def some_function(last_idx):
print(some_arr[:last_idx])
some_arr = range(100)
last_idx = 5
some_function(last_idx)
last_idx = None
@otayeby
otayeby / redirect-stdout-inside-loop.py
Last active April 4, 2018 04:21
Redirecting the stdout to a variable while iterating inside a loop.
"""
Reason for publishing this Gist and the use case:
In many cases we use functions in libraries that print the variable we want instead of returning it. This Gist shows
how to get hold of the printed values from these functions and store in a variable. I found the solution in
couple of posts on different forums:
* https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer
* https://wrongsideofmemphis.wordpress.com/2010/03/01/store-standard-output-on-a-variable-in-python/
* https://groups.google.com/forum/#!topic/comp.lang.python/tkK6n1oVKhM
* https://bytes.com/topic/python/answers/849106-redirection-standard-output-python-command-python-variable
In addition to the trick demonstrated in these posts, I found a case where I would need to store multiple printouts