Useful functions in Python and associated libraries
LIBRARY IMPORTATION
import sys
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
PLAIN PYTHON
number=len(array) Length of an array
number=len(data_frame.index) Number of lines of a dataframe (from pandas)
print(‘\n’) Prints a line-break
print(‘Some text followed by numeric Prints some text (between ‘ ‘ ) and the desired
variables:’,variables) variable
round(number,N) Rounds a float number with N decimals
float(input(‘some text’)) Realizes a user-input in the form of a decimal
number
PYTHON FORMALISM
def function_name(arg1,arg2):
Create a function named “function_name” which
some code takes 2 arguments (arg1 and arg2) and return
return something “something”
while comparison: Create a “while” loop that will execute the code
some code within it until the “comparison” is False
for i in range(number): Create a “for” (numbered) loop which will run a
“number” of times. The variable “i” takes the values
some code
of 0 until number-1
if comparison:
some code
elif comparison2:
If / else if / else comparison scheme
more code
else:
final code
Comparison → == / != / <= / >= Equality, inequality (not equal to) etc.
Compound comparison → and / or Comp1 and Comp2 / Comp1 or Comp2
PANDAS
data_frame=pd.read_excel(io=’file_name’,sheet_name Read an Excel file, at page “sheet_name”, and store
=’sheet_name’) it into a dataframe
data_frame.index Dataframe index → return number of lines
Gives the data contained at position {i,j}
data_frame.iloc[i,j]
!!! Indexes begin at 0,0 in Python !!!
data_frame.iloc[:,j] Gives the data of all lines and column j
NUMPY
vector=np.zeros(N) / vector=np.zeros([N]) Creates a line vector of N components
matrix=np.zeros([N,M]) Creates a matrix of N by M components
tensor=np.zeros([k,N,M]) Creates a 3rd order tensor of kxNxM
vector=np.cross(vecA,vecB) Realizes the cross products between 2 vectors
Gives the data contained at position {i,j}
q[i,j]
!!! Indexes begin at 0,0 in Python !!!
q[:,j] Gives the data of all lines and column j
np.round(vec,n) Rounds all values within vector/matrix (n decimals)
np.linalg.det(matrix) Calculates the determinant of a matrix
np.linalg.inv(matrix) Calculates the inverse of a matrix
np.linalg.inv(matrix).dot(vector) Calculates the dot product between a matrix and a
vector
np.eye(N) Creates a N by N identity matrix
MATPLOTLIB
plt.fill(vecA,vecB,fill=False) Prints closed curve plot from 2 vectors
plt.quiver(xcoord_vec,ycoord_vec,Ex_vec,Ey_vec,angles Prints a vector field (Ex,Ey), with the vector centres
=’xy’,scale_units=’xy’,scale=number) at (xcoord,ycoord) and scale “number”