- Import file in a different/common-used folder
import sys
sys.path.insert(1, '/path/to/application/app/folder')
import file
- Run system commands without using os.system()
import subprocess
subprocess.call(["ls", "-lt"])
This command calls the shell script and returns the system output and return code attribute (e.g., 0 for no error, 1 for error). This will wait for the completed process.
- Use makedirs instead of mkdir
However, of the target directory already exists, raise an OSError if exist_ok is False. Otherwise no exception is raised.
So it is better to check if the directory exists first:
if not os.path.exists(dir):
os.makedirs(dir)
- Open a file without closing it
with open("test.txt") as file:
# Use file to refer to the file object file.write("hello world!") #
Opens file in write mode- Delete a file
- Numpy calculation handling exceptions
# where: broadcast at locations where the condition is true, elsewhere the out array will retain its original value.
# single formula: percent = area/max_area
percent = np.divide(area, max_area, out=np.zeros_like(area), where=max_area!=0)
ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
The first one is preferred because it keeps the original dataframe.
df[df.select_dtypes(include=['number']).columns] *= constant
df.select_dtypes(exclude=['object', 'datetime']) * 3percent = np.divide(area, max_area, out=np.zeros_like(area), where=max_area!=0)
- Find the indices of the largest value
ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
- Merge multiple dataframes
from functools import reduce
coef_full = reduce(lambda left,right: pd.merge(left,right,how='left'), [llp_df, slp_df, vslp_df])- Multiply a constant/column to the numeric values of an existing dataframe
The first one is preferred because it keeps the original dataframe.
df[df.select_dtypes(include=['number']).columns] *= constant
No comments:
Post a Comment