Cheetsheet
Contents
Cheetsheet¶
General¶
Getting help:
help(my_function)
,help(my_module.my_function)
,help(my_variable.my_method)
Import a module:
import my_module
orimport my_module as mm
Import a function from a module:
from my_module import my_function
Creating a function:
def my_function(a, b = 3):
my_output = a * b
return my_output
Creating a for loop:
for i in my_list:
do something with each i element of my_list
each line does some operation
there can be multiple lines
all lines have to be INDENTED
for i in range(10):
do something with i which takes values from 0 to 9
Creating an if statement:
if a > b:
do something if a > b
elif a > c:
if the first condition is unmet, do something if a > c
else:
in all other cases do another operation
each bloch can have multiple lines
as in the for loop, the blocks have to be INDENTED
Having multiple blocks:
for i in my_list:
print(i)
if i > 5:
new_var = i * 2
Numpy¶
Create zeros array:
my_array = np.zeros((5,7))
Get value at row = 3, column = 4:
my_value = my_array[3,4]
Get all columns of row = 3:
my_array[3,:]
Create boolean array by a logical operation:
my_boolean_array = my_array > 10
Check array size:
my_array.shape
Get pixel values of image under mask:
pixel_values = image[mask]
Flatten an array (make it 1D):
array_1D = np.ravel(my_array)
Matplotlib¶
Plot an image:
plt.subplots(figsize=(10,10))
plt.imshow(my_image)
plt.show()
Histogram with specific bins:
plt.hist(my_data, bins = np.arange(0,1000,1))
plt.show()
Pandas¶
Create a Dataframe from list of dictionaries:
my_dataframe = pd.DataFrame(my_dictlist)
Create a Dataframe from a 2D array with three columns:
my_dataframe = pd.DataFrame(my_2Darray, columns=['col1','col2','col3'])
Recover a the my_param column for all rows:
my_dataframe.my_param
ormy_dataframe['my_param']
Calculate mean of a column called my_param:
my_dataframe.my_param.mean()
Calculate statistic for full table:
my_dataframe.mean()
Skimage¶
Import an image from your computer:
skimage.io.imread('/path/to/your/file.tif')
Import an image from the web:
skimage.io.imread('http://mysite/my_image.tif')