Skip to content

Instantly share code, notes, and snippets.

Avatar

Omar ElTayeby otayeby

View GitHub Profile
@otayeby
otayeby / gen_contingency_table.py
Last active Mar 18, 2021
Generate the contingency table for 2 categorical variables in a Pandas DataFrame
View gen_contingency_table.py
# 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 Apr 11, 2018
Using None to index all elements
View passing-last-index.py
"""
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 Apr 4, 2018
Redirecting the stdout to a variable while iterating inside a loop.
View redirect-stdout-inside-loop.py
"""
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