markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Problem variant1: Search a sorted array for first occurrence of target(k) Given an array(A) of numbers sorted in increasing order, implement a function that returns the index of the first occurence of a target(k) if found in A, and -1 otherwise. | A = [5, 8, 8, 8, 8, 19, 30, 35, 40, 51]
def first_occurence_search(A, k):
left, right, res = 0, len(A)-1, -1
while left<=right:
mid = (right - left)//2 + left
if A[mid] < k:
#look on the right
left = mid+1
elif A[mid] > k:
#look on the left
... | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Problem variant2: Search a sorted array for entry equal to its index Given a sorted array(A) of distinct integers, implement a function that returns the index i if A[i] = i, and -1 otherwise. | A = [-3, 0, 2, 5, 7, 9, 18, 35, 40, 51]
def search_entry_equal_to_its_index(A):
left, right = 0, len(A)-1
while left<=right:
mid = (right - left)//2 + left
difference = A[mid] - mid
if difference < 0:
#look on the right
left = mid+1
elif difference > 0:
... | _____no_output_____ | MIT | geekgap_webinars/notebooks/webinar_1/algorithms_data_structures.ipynb | geekgap-io/geekgap_webinars |
Pathlib Object oriented Pythonic pathsaka"The Right Way to do Paths"https://docs.python.org/3/library/pathlib.html | # Pathlib is a standard Python library
# You will usually want to import Path and/or PurePath
import pathlib
from pathlib import Path, PurePath
# Let's do a few more imports for later
import os
import shutil | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
What _are_ paths, really?Depends on the context. Is this a path?It's certainly a URL...https://autumn-data.com/runs/sm_sir/How about just this bit? sm_sir/malaysia/1634732134/ec182fPaths are abstract representations of a nested, tree-like structure Such things include filesystems, bits of web addresses, certain rep... | cwd = Path()
cwd
# Listdir
os.listdir(cwd)
cwd.glob('*')
list(cwd.glob('*'))
# Making glob a little easier to work with; the autumn display module contains
# some hooks for Jupyter notebooks
from autumn.tools.utils import display
cwd.glob('*')
cd ..
cwd.glob('*')
cd workshops/
cwd = cwd.absolute()
cwd
# This will work... | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
A note on being a good programmer...The string examples above tell us something - we all make assumptions, that turn into heuristics - they work well, until they don't It's not about being a "rockstar"... more like a buddhist monk with a management jobLearn how to delegate - use system libraries! Someone else has thou... | test_path = cwd / "test_files"
test_path.mkdir(exist_ok=True)
for i in range(5):
(test_path / f"file{i}.txt").write_text(f"Some example file contents for file {i}")
contents_map = {f: f.read_text() for f in cwd.glob("*/*.txt")}
contents_map
# Bonus Python 3.8 syntax - the Walrus operator :=
{f: contents for f in cw... | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
Writing functions, calling functions | def do_something1(path_to_file):
return os.path.exists(path_to_file)
def do_something2(path_to_file):
return path_to_file.exists()
do_something1(test_path)
do_something2(test_path)
a_file = "this is not a file"
do_something1(a_file)
do_something2(a_file) | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
Use type annotations! (You should be doing this anyway) | def do_something3(path_to_file: Path) -> bool:
# Users know what this function expects
return path_to_file.exists()
# This will fail - but it's the user's fault now (in the nicest possible way...)
do_something3(a_file)
do_something3(Path(a_file))
from typing import Union
def do_something4(path_to_file: Union[P... | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
PurePathsPurePaths are 'pure' in that they are a) Abstract representations unencumbered by the weight of the real world... b) Functionally pure (ie they can't produce side effects) | from pathlib import PurePath, PurePosixPath, PureWindowsPath
# Use PurePath directly if you want to work on abstract paths of the type of system you're working on...
pure_test = PurePath(test_path)
pure_test
pure_test.mkdir()
# Specify the path type if you have a particular filesystem in mind...
win_path = PureWindow... | _____no_output_____ | BSD-2-Clause-FreeBSD | notebooks/workshops/04Pathlib.ipynb | emmamcbryde/AuTuMN-1 |
We are penalizing wrong classification with higher cost | # Defining logistic Regrssion Class
class logisticRegression():
def __init__(self, eta = 0.1, n_iter = 50, random_state = 1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self,X,y):
#shape of X = [n_examples, n_features]
#shape of... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/Logistic Regression-checkpoint.ipynb | AshishSinha5/mlAlgos |
import glob
python_files = glob.glob('*.py')
for file_name in sorted(python_files):
print (' ------' + file_name)
with open(file_name) as f:
for line in f:
print (' ' + line.rstrip())
print() | _____no_output_____ | MIT | opening_files.ipynb | aditya270520/100Daysofpython | |
Convert data extracted from Frost PurposeConvert data that can be extracted from MET observation storage through the Frost API https://frost.met.no/index.html. The extraction process is not documented. Import the necessary packages. | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | CC-BY-4.0 | notebooks/convert_met_obs.ipynb | NorDataNet/TrainingMaterial |
Read the actual data file that has been extracted from the Frost API described above. | mydf = pd.read_csv('radflux-bjørnøya-frost.txt', header=0,mangle_dupe_cols=True, parse_dates=['referenceTime'], index_col='referenceTime', na_values=['-']) | _____no_output_____ | CC-BY-4.0 | notebooks/convert_met_obs.ipynb | NorDataNet/TrainingMaterial |
Dump an overview of the data that has been read. | mydf.keys()
mydf | _____no_output_____ | CC-BY-4.0 | notebooks/convert_met_obs.ipynb | NorDataNet/TrainingMaterial |
Plot the dataset. | fig = plt.figure(figsize=(20,10))
mydf.plot.line(y=['mean(surface_downwelling_shortwave_flux_in_air pt1m)(W/m2)','mean(surface_downwelling_longwave_flux_in_air pt1m)(W/m2)']) | _____no_output_____ | CC-BY-4.0 | notebooks/convert_met_obs.ipynb | NorDataNet/TrainingMaterial |
Ensembling different models | from google.cloud import storage
from io import BytesIO
client = storage.Client()
storage_client = storage.Client(project = 'irkml1')
bucket = storage_client.get_bucket("aindstorm_bucket")
blob1 = storage.blob.Blob("train_3lags_semibalanced.csv",bucket)
content1 = blob1.download_as_string()
blob2 = storage.blob.Blob("... | _____no_output_____ | MIT | random_forest + final output.ipynb | Aindstorm/Deep-behavioral-analysis |
Differentially Private CovarianceSmartNoise offers three different functionalities within its `covariance` function:1. Covariance between two vectors2. Covariance matrix of a matrix3. Cross-covariance matrix of a pair of matrices, where element $(i,j)$ of the returned matrix is the covariance of column $i$ of the left... | # load libraries
import os
import opendp.smartnoise.core as sn
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# establish data information
data_path = os.path.join('.', 'data', 'PUMS_california_demographics_1000', 'data.csv')
var_names = ["age", "sex", "educ", "race", "in... | _____no_output_____ | MIT | analysis/covariance.ipynb | AdrienRoyer/smartnoise-samples |
FunctionalityBelow we show the relationship between the three methods by calculating the same covariance in each. We use a much larger $\epsilon$ than would ever be used in practice to show that the methods are consistent with one another. | with sn.Analysis() as analysis:
wn_data = sn.Dataset(path = data_path, column_names = var_names)
# get scalar covariance
age_income_cov_scalar = sn.dp_covariance(left = sn.to_float(wn_data['age']),
right = sn.to_float(wn_data['income']),
... | scalar covariance:
[[94601.1327106]]
covariance matrix:
[[3.14917795e+02 9.46406149e+04]
[9.46406149e+04 2.65091456e+09]]
cross-covariance matrix:
[[3.14928928e+02 9.50137258e+04]
[9.46392159e+04 2.65184060e+09]]
| MIT | analysis/covariance.ipynb | AdrienRoyer/smartnoise-samples |
DP Covariance in Practice We now move to an example with a much smaller $\epsilon$. | with sn.Analysis() as analysis:
wn_data = sn.Dataset(path = data_path, column_names = var_names)
# get full covariance matrix
cov = sn.dp_covariance(data = sn.to_float(wn_data['age', 'sex', 'educ', 'income', 'married']),
privacy_usage = {'epsilon': 1.},
... | _____no_output_____ | MIT | analysis/covariance.ipynb | AdrienRoyer/smartnoise-samples |
Notice that the differentially private correlation matrix contains values outside of the feasible range for correlations, $[-1, 1]$. This is not uncommon, especially for analyses with small $\epsilon$, and is not necessarily indicative of a problem. In this scenario, we will not use these correlations for anything othe... | '''income = alpha + beta * educ'''
# find DP estimate of beta
beta_hat_dp = dp_cov[2,3] / dp_cov[2,2]
beta_hat = non_dp_cov[2,3] / non_dp_cov[2,2]
print('income = alpha + beta * educ')
print('DP coefficient: {0}'.format(beta_hat_dp))
print('Non-DP Coefficient: {0}'.format(beta_hat)) | income = alpha + beta * educ
DP coefficient: -10900.063151950144
Non-DP Coefficient: 4601.803740280991
| MIT | analysis/covariance.ipynb | AdrienRoyer/smartnoise-samples |
Tutorials Installation:https://caffe2.ai/docs/tutorials.htmlFirst download the tutorials source. from google.colab import drive drive.mount('/content/drive') %cd /content/drive/My Drive/ !git clone --recursive https://github.com/caffe2/tutorials caffe2_tutorials Model QuickloadThis notebook will show you how to quick... | from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/My Drive/caffe2_tutorials
!pip3 install torch torchvision
!python -m caffe2.python.models.download -i squeezenet
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ im... | _____no_output_____ | MIT | Model_Quickload.ipynb | mashyko/object_detection |
Dynamic Double Machine Learning: Use Cases and ExamplesDynamic DoubleML is an extension of the Double ML approach for treatments assigned sequentially over time periods. This estimator will account for treatments that can have causal effects on future o... | %load_ext autoreload
%autoreload 2
import econml
# Main imports
from econml.dynamic.dml import DynamicDML
from econml.tests.dgp import DynamicPanelDGP, add_vlines
# Helper imports
import numpy as np
from sklearn.linear_model import Lasso, LassoCV, LogisticRegression, LogisticRegressionCV, MultiTaskLassoCV
import matpl... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
1. Example Usage with Average Treatment Effects 1.1 DGPWe consider a data generating process from a markovian treatment model. In the example bellow, $T_t\rightarrow$ treatment(s) at time $t$, $Y_t\rightarrow$outcome at time $t$, $X_t\rightarrow$ features and controls at time $t$ (the coefficients $e, f$ will pick th... | # Define DGP parameters
np.random.seed(123)
n_panels = 5000 # number of panels
n_periods = 3 # number of time periods in each panel
n_treatments = 2 # number of treatments in each period
n_x = 100 # number of features + controls
s_x = 10 # number of controls (endogeneous variables)
s_t = 10 # treatment support size
# G... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
1.2 Train Estimator | est = DynamicDML(
model_y=LassoCV(cv=3, max_iter=1000),
model_t=MultiTaskLassoCV(cv=3, max_iter=1000),
cv=3)
est.fit(Y, T, X=None, W=W, groups=groups)
# Average treatment effect of all periods on last period for unit treatments
print(f"Average effect of default policy: {est.ate():0.2f}")
# Effect of targe... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
1.3 Performance Visualization | # Some plotting boilerplate code
plt.figure(figsize=(15, 5))
plt.errorbar(np.arange(n_periods*n_treatments)-.04, est.intercept_, yerr=(conf_ints[1] - est.intercept_,
est.intercept_ - conf_ints[0]), fmt='o', label='DynamicDML')
plt.errorbar(np.arange(n_periods*n_treatm... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
2. Example Usage with Heterogeneous Treatment Effects on Time-Invariant Unit CharacteristicsWe can also estimate treatment effect heterogeneity with respect to the value of some subset of features $X$ in the initial period. Heterogeneity is currently only supported with respect to such initial state features. This for... | # Define additional DGP parameters
het_strength = .5
het_inds = np.arange(n_x - n_treatments, n_x)
# Generate data
dgp = DynamicPanelDGP(n_periods, n_treatments, n_x).create_instance(
s_x, hetero_strength=het_strength, hetero_inds=het_inds, random_seed=12)
Y, T, X, W, groups = dgp.observational_data(n_panel... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
2.2 Train Estimator | est = DynamicDML(
model_y=LassoCV(cv=3),
model_t=MultiTaskLassoCV(cv=3),
cv=3)
est.fit(Y, T, X=X, W=W, groups=groups, inference="auto")
est.summary()
# Average treatment effect for test points
X_test = X[np.arange(0, 25, 3)]
print(f"Average effect of default policy:{est.ate(X=X_test):0.2f}")
# Effect of t... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
2.3 Performance Visualization | # parse true parameters in array of shape (n_treatments*n_periods, 1 + n_hetero_inds)
# first column is the intercept
true_effect_inds = []
for t in range(n_treatments):
true_effect_inds += [t * (1 + n_x)] + (list(t * (1 + n_x) + 1 + het_inds) if len(het_inds)>0 else [])
true_effect_params = dgp.true_hetero_effect[... | _____no_output_____ | BSD-3-Clause | notebooks/Dynamic Double Machine Learning Examples.ipynb | GildasTiwangNg/EconML |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
file_to_load = "Resources/purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)
purchase_data.head() | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Player Count * Display the total number of players | total_unique_players=purchase_data['SN'].nunique
#total_unique_players()
total_players_df = pd.DataFrame({"Total Players": [total_unique_players()]})
total_players_df | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc.* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | unique_items=purchase_data['Item ID'].nunique()
#unique_items
average_price=purchase_data['Price'].mean()
#average_price
total_purchases=purchase_data['SN'].count()
#total_purchases
total_revenue=purchase_data['Price'].sum()
#total_revenue
basic_calculations_df=pd.DataFrame({'Number of Unique Items': [unique_items], 'A... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Gender Demographics * Percentage and Count of Male Players* Percentage and Count of Female Players* Percentage and Count of Other / Non-Disclosed | gender_df=purchase_data.groupby('Gender')
gender_df
total_gender_count =gender_df.nunique()['SN']
total_gender_count
percentage_of_players = total_gender_count / total_unique_players() * 100
percentage_of_players
final_gender_df = pd.DataFrame({'Total Count': total_gender_count, 'Percentage of Players': percentage_o... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame | #Create dataframe to complete gender analysis
gender_analysis = gender_df[['SN','Gender', 'Age','Purchase ID', 'Price']]
gender_analysis
#Create variables to hold values for purchase count avg price by gender, purchase value total by gender, and average total price per person
total_purchase_count=gender_df['Purchase I... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Age Demographics * Establish bins for ages* Categorize the existing players using the age bins. Hint: use pd.cut()* Calculate the numbers and percentages by age group* Create a summary data frame to hold the results* Optional: round the percentage column to two decimal points* Display Age Demographics Table | #Create age DF to work with data
#age_df=purchase_data.groupby['Age']
#age_df
# Create bins in which to place values based upon ages of users
bins = [0, 9.99, 14.99, 19.99, 24.99,29.99, 34.99, 39.99 ,99.99]
# Create labels for these bins
group_labels = ['<10', '10 to 14', '15 to 19','20 to 24', '25 to 29', '30 to 34'... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Purchasing Analysis (Age) * Bin the purchase_data data frame by age* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary d... | #Create variables for the purchasing analysis for Purchase Count, Average Purchase Price, Total Purchase Value, Avg Total Purchase per Person
age_purchase_count=group_ages['Purchase ID'].count()
age_purchase_count
age_avg_purchase_price=group_ages['Price'].mean()
age_avg_purchase_price
age_purchase_value=group_ages['... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Top Spenders * Run basic calculations to obtain the results in the table below* Create a summary data frame to hold the results* Sort the total purchase value column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame | #Use the DF above to find the top spenders
#Start by grouping results by SN
SN_group=purchase_data.groupby('SN')
SN_group
#Create varialbe to hold the results that will fill the summary table
purchase_count=SN_group['Purchase ID'].count()
purchase_count
avg_purchase_price_by_SN=SN_group['Price'].mean().round(2)
avg_p... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns* Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value* Create a summary data frame to hold the results* Sort the purchase count column in descending order* Optional: give the disp... | #Create a new data frame to retrieve Item ID, Item Name, and Item Price columns
popular_items=purchase_data[['Item ID', 'Item Name', 'Price']]
popular_items
#Create a groupby to hold the results
grouped_data=popular_items.groupby(['Item ID', 'Item Name'])
grouped_data
#Complete basic calculations
purchase_count_popul... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Most Profitable Items * Sort the above table by total purchase value in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the data frame | #Sort the above table by total purchase value in descending order
most_popular_items_df_sorted_pv=most_popular_items_df.sort_values(['Total Purchase Value'], ascending=False).head()
most_popular_items_df_sorted_pv
#Give currency formatting to the Item Price and Total Purchase Value Column
most_popular_items_df_sorted_... | _____no_output_____ | ADSL | HeroesOfPymoli/HeroesOfPymoli_starter.ipynb | juliedundas/pandas-challenge |
Saint Lucia* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Saint-Lucia.ipynb) | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview("Saint Lucia", weeks=5);
overview("Saint Lucia");
compare_plot("Saint Lucia", n... | _____no_output_____ | CC-BY-4.0 | ipynb/Saint-Lucia.ipynb | skirienko/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Saint-Lucia.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Saint-Lucia.ipynb | skirienko/oscovida.github.io |
Correlation What is correlation?Correlation is a statistical term which in common usage refers to how close two variables are to having a linear relationship with each other.For example, two variables which are linearly dependent (say, **x** and **y** which depend on each other as x = 2y) will have a higher correlati... | import numpy as np
import pandas as pd
import seaborn as sns | _____no_output_____ | MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Loading the dataset | data = pd.read_csv('./Datasets/Data_for_Correlation.csv')
data.head() | _____no_output_____ | MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Removing the Class Label entry (Y) | data = data.iloc[:,:-1]
data.head()
data.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 14 entries, 0 to 13
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 X1 14 non-null int64
1 X2 14 non-null int64
2 X3 14 non-null int64
3 X4 14 non-null int64
dtypes: ... | MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Selecting features based on correlationGenerating the correlation matrix | corr = data.corr()
corr.head() | _____no_output_____ | MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Generating the correlation heatmap | sns.heatmap(corr) | _____no_output_____ | MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Next, we compare the correlation between features and remove one of two features that have a correlation higher than 0.9 | columns = np.full((corr.shape[0],), True, dtype=bool)
for i in range(corr.shape[0]):
for j in range(i+1, corr.shape[0]):
if corr.iloc[i,j] >= 0.9:
if columns[j]:
columns[j] = False
selected_columns = data.columns[columns]
selected_columns.shape
data = data[selected_columns]
print... | X1 X4
0 1 -2
1 2 -4
2 3 3
3 4 4
4 5 25
5 6 76
6 7 34
7 8 346
8 9 67
9 10 3
10 11 355
11 12 88
12 13 2
13 14 1
| MIT | Lab-2/4feature-selection-correlation.ipynb | yash-a-18/002_YashAmethiya |
Cox Proportional Hazard> SA with features apart from timeWe model the the instantaneous hazard as the product of two functions, one with the time component, and the other with the feature component.$$\begin{aligned}\lambda(t,x) = \lambda(t)h(x)\end{aligned}$$It is important to have the seperation of these functions to... | # export
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.preprocessing import MaxAbsScaler, StandardScaler
from torchlife.losses import hazard_loss
from torchlife.models.ph import PieceWiseHazard
# torch.Tensor.ndim = property(lambda x... | _____no_output_____ | Apache-2.0 | 59_hazard.Cox.ipynb | sachinruk/torchlife2 |
Fitting Cox Proportional Hazard Model | # hide
from torchlife.data import create_db, get_breakpoints
import pandas as pd
# hide
url = "https://raw.githubusercontent.com/CamDavidsonPilon/lifelines/master/lifelines/datasets/rossi.csv"
df = pd.read_csv(url)
df.head()
# hide
df.rename(columns={'week':'t', 'arrest':'e'}, inplace=True)
breakpoints = get_breakpoint... | _____no_output_____ | Apache-2.0 | 59_hazard.Cox.ipynb | sachinruk/torchlife2 |
Plotting hazard functions | model.baseλ.plot_hazard()
x = df.drop(['t', 'e'], axis=1).iloc[4]
t = np.arange(df['t'].max())
model.plot_survival_function(t, x)
# hide
from nbdev.export import *
notebook2script() | Converted 00_index.ipynb.
Converted 10_SAT.ipynb.
Converted 20_KaplanMeier.ipynb.
Converted 50_hazard.ipynb.
Converted 55_hazard.PiecewiseHazard.ipynb.
Converted 59_hazard.Cox.ipynb.
Converted 60_AFT_models.ipynb.
Converted 65_AFT_error_distributions.ipynb.
Converted 80_data.ipynb.
Converted 90_model.ipynb.
Converted 9... | Apache-2.0 | 59_hazard.Cox.ipynb | sachinruk/torchlife2 |
NetCDF file First you have to import the meteomatics module and the datetime module | import datetime as dt
import meteomatics.api as api | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
Input here your username and password from your meteomatics profile | ###Credentials:
username = 'python-community'
password = 'Umivipawe179' | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
Input here the limiting coordinates of the extract you want to look at. You can also change the resolution. | lat_N = 50
lon_W = -16
lat_S = 20
lon_E = 10
res_lat = 2
res_lon = 2 | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
Input here the directory and the name. The directory must already exist. | filename_nc = 'path_netcdf/netcdf_file.nc' | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
Input here the startdate, enddate and the timeinterval as datetime objects. | startdate_nc = dt.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
enddate_nc = startdate_nc + dt.timedelta(days=3)
interval_nc = dt.timedelta(hours=12) | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
Choose the parameter you want to get. You can only chose one parameter at a time. Check here which parameters are available: https://www.meteomatics.com/en/api/available-parameters/ | parameter_nc = 't_2m:C' | _____no_output_____ | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
In the following, the request will start. If there is an error in the request as for example a wrong parameter or a date that doesn't exist, you get a message. | print("netCDF file:")
try:
api.query_netcdf(filename_nc, startdate_nc, enddate_nc, interval_nc, parameter_nc, lat_N, lon_W, lat_S,
lon_E, res_lat, res_lon, username, password)
print("filename = {}".format(filename_nc))
except Exception as e:
print("Failed, the exception is {}".format(e)... |
netCDF file:
2019-04-10 10:04:39| INFO |Calling URL: https://api.meteomatics.com/2019-04-10T00:00:00+00:00--2019-04-13T00:00:00+00:00:PT12H/t_2m:C/50,-16_20,10:2,2/netcdf?connector=python_2.0.1 (username = python-community)
2019-04-10 10:04:39| INFO |Create Path: path_netcdf
2019-04-10 10:04:39| INFO |Create File path... | MIT | examples/notebooks/08_Net_CDF_file.ipynb | schluchc/python-connector-api |
(*** hide ***) |
#nowarn "211"
open System
let airQuality = __SOURCE_DIRECTORY__ + "/data/airquality.csv"
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**Interoperating between R and Deedle===================================The [R type provider](http://fslab.org/RProvider/) enablessmooth interoperation between R and F. The type provider automatically discovers installed packages and makes them accessible via the `RProvider` namespace.R type provider for F automatical... |
#load "../../packages/RProvider/RProvider.fsx"
#load "../../bin/net45/Deedle.fsx"
open RProvider
open RDotNet
open Deedle
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**If you're not using NuGet from Visual Studio, then you'll need to manually copy thefile `Deedle.RProvider.Plugin.dll` from the package `Deedle.RPlugin` to the directory where `RProvider.dll` is located (in `RProvider/lib`). Once that'sdone, the R provider will automatically find the plugin.Passing data frames to and... |
open RProvider.datasets
// Get mtcars as an untyped object
R.mtcars.Value
// Get mtcars as a typed Deedle frame
let mtcars : Frame<string, string> = R.mtcars.GetValue()
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(*** include-value:mtcars ***) (**The first sample uses the `Value` property to convert the data set to a boxed Deedleframe of type `obj`. This is a great way to explore the data, but when you want to do some further processing, you need to specify the type of the data frame that you wantto get. This is done on line 7 ... |
#load "../../packages/FSharp.Charting/lib/net45/FSharp.Charting.fsx"
open FSharp.Charting
mtcars
|> Frame.groupRowsByInt "gear"
|> Frame.getCol "mpg"
|> Stats.levelMean fst
|> Series.observations |> Chart.Column
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(*** include-it:mpgch ***) (** From Deedle to RSo far, we looked how to turn R data frame into Deedle `Frame`, so let's lookat the opposite direction. The following snippet first reads Deedle data frame from a CSV file (file name is in the `airQuality` variable). We can then use thedata frame as argument to standard R ... |
let air = Frame.ReadCsv(airQuality, separators=";")
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(*** include-value:air ***) (**Let's first try passing the `air` frame to the R `as.data.frame` function (which will not do anything, aside from importing the data into R). To do something slightly more interesting, we then use the `colMeans` R function to calculate averagesfor each column (to do this, we need to open ... |
open RProvider.``base``
// Pass air data to R and print the R output
R.as_data_frame(air)
// Pass air data to R and get column means
R.colMeans(air)
// [fsi:val it : SymbolicExpression =]
// [fsi: Ozone Solar.R Wind Temp Month Day ]
// [fsi: NaN NaN 9.96 77.88 6.99 15.8]
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(** As a final example, let's look at the handling of missing values. Unlike R, Deedle does not distinguish between missing data (`NA`) and not a number (`NaN`). For example, in the following simple frame, the `Floats` column has missing value for keys 2 and 3 while`Names` has missing value for the row 2:*) |
// Create sample data frame with missing values
let df =
[ "Floats" =?> series [ 1 => 10.0; 2 => nan; 4 => 15.0]
"Names" =?> series [ 1 => "one"; 3 => "three"; 4 => "four" ] ]
|> frame
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**When we pass the data frame to R, missing values in numeric columns are turned into `NaN`and missing data for other columns are turned into `NA`. Here, we use `R.assign` whichstores the data frame in a varaible available in the current R environment:*) |
R.assign("x", df)
// [fsi:val it : SymbolicExpression = ]
// [fsi: Floats Names ]
// [fsi: 1 10 one ]
// [fsi: 2 NaN <NA> ]
// [fsi: 4 15 four ]
// [fsi: 3 NaN three ]
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**Passing time series to and from R---------------------------------For working with time series data, the Deedle plugin uses [the zoo package](http://cran.r-project.org/web/packages/zoo/index.html) (Z's ordered observations). If you do not have the package installed, you can do thatby using the `install.packages("zoo... |
R.austres.Value
// [fsi:val it : obj =]
// [fsi: 1971.25 -> 13067.3 ]
// [fsi: 1971.5 -> 13130.5 ]
// [fsi: 1971.75 -> 13198.4 ]
// [fsi: ... -> ... ]
// [fsi: 1992.75 -> 17568.7 ]
// [fsi: 1993 -> 17627.1 ]
// [fsi: 1993.25 -> 17661.5 ]
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**As with data frames, when we want to do any further processing with the time series, we needto use the generic `GetValue` method and specify a type annotation to that tells the Fcompiler that we expect a series where both keys and values are of type `float`:*) |
// Get series with numbers of australian residents
let austres : Series<float, float> = R.austres.GetValue()
// Get TimeSpan representing (roughly..) two years
let twoYears = TimeSpan.FromDays(2.0 * 365.0)
// Calculate means of sliding windows of 2 year size
austres
|> Series.mapKeys (fun y ->
DateTime(int y,... | _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**The current version of the Deedle plugin supports only time series with single column.To access, for example, the EU stock market data, we need to write a short R inlinecode to extract the column we are interested in. The following gets the FTSE time series from `EuStockMarkets`:*) |
let ftseStr = R.parse(text="""EuStockMarkets[,"FTSE"]""")
let ftse : Series<float, float> = R.eval(ftseStr).GetValue()
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(** From Deedle to RThe opposite direction is equally easy. To demonstrate this, we'll generate a simpletime series with 3 days of randomly generated values starting today:*) |
let rnd = Random()
let ts =
[ for i in 0.0 .. 100.0 ->
DateTime.Today.AddHours(i), rnd.NextDouble() ]
|> series
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**Now that we have a time series, we can pass it to R using the `R.as_zoo` function orusing `R.assign` to store it in an R variable. As previously, the R provider automaticallyshows the output that R prints for the value:*) |
open RProvider.zoo
// Just convert time series to R
R.as_zoo(ts)
// Convert and assing to a variable 'ts'
R.assign("ts", ts)
// [fsi:val it : string =
// [fsi: 2013-11-07 05:00:00 2013-11-07 06:00:00 2013-11-07 07:00:00 ...]
// [fsi: 0.749946652 0.580584353 0.523962789 ...]
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**Typically, you will not need to assign time series to an R variable, because you can use it directly as an argument to functions that expect time series. For example, thefollowing snippet applies the rolling mean function with a window size 20 to the time series.*) |
// Rolling mean with window size 20
R.rollmean(ts, 20)
| _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**This is a simple example - in practice, you can achieve the same thing with `Series.window`function from Deedle - but it demonstrates how easy it is to use R packages with time series (and data frames) from Deedle. As a final example, we create a data frame thatcontains the original time series together with the rol... |
// Use 'rollmean' to calculate mean and 'GetValue' to
// turn the result into a Deedle time series
let tf =
[ "Input" => ts
"Means5" => R.rollmean(ts, 5).GetValue<Series<_, float>>()
"Means20" => R.rollmean(ts, 20).GetValue<Series<_, float>>() ]
|> frame
// Chart original input and the two rolling mean... | _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk |
(**Depending on your random number generator, the resulting chart looks something like this:*) (*** include-it:means ***) | _____no_output_____ | MIT | notebooks/other/Deedle/rinterop.ipynb | SpaceAntelope/IfCntk | |
FloPy Creating a Simple MODFLOW 6 Model with FlopyThe purpose of this notebook is to demonstrate the Flopy capabilities for building a simple MODFLOW 6 model from scratch, running the model, and viewing the results. This notebook will demonstrate the capabilities using a simple lake example. A separate notebook is a... | import sys
import os
import platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# run installed version of flopy or add local path
try:
import flopy
except:
fpth = os.path.abspath(os.path.join('..', '..'))
sys.path.append(fpth)
import flopy
print(sys.version)
print('nu... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Create the Flopy Model ObjectsWe are creating a square model with a specified head equal to `h1` along all boundaries. The head at the cell in the center in the top layer is fixed to `h2`. First, set the name of the model and the parameters of the model: the number of layers `Nlay`, the number of rows and columns `N`,... | name = 'mf6lake'
h1 = 100
h2 = 90
Nlay = 10
N = 101
L = 400.0
H = 50.0
k = 1.0 | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
One big difference between MODFLOW 6 and previous MODFLOW versions is that MODFLOW 6 is based on the concept of a simulation. A simulation consists of the following:* Temporal discretization (TDIS)* One or more models (GWF is the only model supported at present)* Zero or more exchanges (instructions for how models are... | # Create the Flopy simulation object
sim = flopy.mf6.MFSimulation(sim_name=name, exe_name='mf6',
version='mf6', sim_ws=workspace)
# Create the Flopy temporal discretization object
tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=1,
... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Now that the overall simulation is set up, we can focus on building the groundwater flow model. The groundwater flow model will be built by adding packages to it that describe the model characteristics.Define the discretization of the model. All layers are given equal thickness. The `bot` array is build from `H` and t... | # Create the discretization package
bot = np.linspace(-H/Nlay, -H, Nlay)
delrow = delcol = L/(N-1)
dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=Nlay, nrow=N, ncol=N,
delr=delrow,delc=delcol,top=0.0,
b... | Help on ModflowGwfoc in module flopy.mf6.modflow.mfgwfoc object:
class ModflowGwfoc(flopy.mf6.mfpackage.MFPackage)
| ModflowGwfoc(model, loading_package=False, budget_filerecord=None, head_filerecord=None, headprintrecord=None, saverecord=None, printrecord=None, filename=None, pname=None, parent_file=None)
|
| ... | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Create the MODFLOW 6 Input Files and Run the ModelOnce all the flopy objects are created, it is very easy to create all of the input files and run the model. | # Write the datasets
sim.write_simulation()
# Print a list of the files that were created
# in workspace
print(os.listdir(workspace)) | ['mf6lake.oc', 'mf6lake.nam', 'mf6lake.dis', 'mf6lake.ims', 'mf6lake.chd', 'mf6lake.npf', 'mf6lake.ic', 'mfsim.nam', 'mf6lake.tdis']
| CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Run the SimulationWe can also run the simulation from the notebook, but only if the MODFLOW 6 executable is available. The executable can be made available by putting the executable in a folder that is listed in the system path variable. Another option is to just put a copy of the executable in the simulation folder... | # Run the simulation
success, buff = sim.run_simulation()
print('\nSuccess is: ', success) | FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6
MODFLOW 6
U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL
VERSION 6.2.0 10/22/2020
MODFLOW 6 compiled Oct 25 2020 16:15:39 with IFORT compiler (ver... | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Post-Process Head ResultsPost-processing MODFLOW 6 results is still a work in progress. There aren't any Flopy plotting functions built in yet, like they are for other MODFLOW versions. So we need to plot the results using general Flopy capabilities. We can also use some of the Flopy ModelMap capabilities for MODFL... | # Read the binary head file and plot the results
# We can use the existing Flopy HeadFile class because
# the format of the headfile for MODFLOW 6 is the same
# as for previous MODFLOW verions
fname = os.path.join(workspace, headfile)
hds = flopy.utils.binaryfile.HeadFile(fname)
h = hds.get_data(kstpkper=(0, 0))
x = y ... | _____no_output_____ | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
Post-Process FlowsMODFLOW 6 writes a binary grid file, which contains information about the model grid. MODFLOW 6 also writes a binary budget file, which contains flow information. Both of these files can be read using Flopy capabilities. The MfGrdFile class in Flopy can be used to read the binary grid file. The C... | # read the binary grid file
fname = os.path.join(workspace, '{}.dis.grb'.format(name))
bgf = flopy.utils.mfgrdfile.MfGrdFile(fname)
# data read from the binary grid file is stored in a dictionary
bgf._datadict
# Information from the binary grid file is easily retrieved
ia = bgf._datadict['IA'] - 1
ja = bgf._datadict['... | Printing flows for cell 56106
Cell 56106 flow with cell 45905 is -0.0002858449337963975
Cell 56106 flow with cell 56005 is -0.025019694309449392
Cell 56106 flow with cell 56105 is -0.025019694309449392
Cell 56106 flow with cell 56107 is 0.025058524820593675
Cell 56106 flow with cell 56207 is 0.02505852482066473
Cell 56... | CC0-1.0 | examples/Notebooks/flopy3_mf6_A_simple-model.ipynb | tomvansteijn/flopy |
As a self-taught Data Scientist and programmer, I always get asked about how I started my path towards learning, and a lot of non-coders ask me about how they can learn more about Data Science. And while I tell them about the umpteen Data Analytics and Data Visualization tools, various Machine Learning algorithms, and ... | print('Hello, World!')
print("Python is great") | Hello, World!
Python is great
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Displaying blank lines Blank lines make the output more readable. For a blank line, you can insert a `print` function with nothing inside. Each `print` function prints on a new line by default. You can also use `\n` (the newline character) to print a new line at the end of a string or right in the middle of a string. | print('Hello')
print()
print('Above is a blank line\n')
print('Blank line \nin the middle of a string') | Hello
Above is a blank line
Blank line
in the middle of a string
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
--- Getting information from the userYou can use the `input` to ask for information from your user. We pass in a message with the `input` function. | name = input('What is your name? ')
print(name) | What is your name? Pranav
Pranav
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Here, whatever value is typed in by the user will be stored in the variable `name` and can be used as needed. We've chosen to print the value of `name` on the screen. --- CommentsComments are a way of documenting your code. Comments can be added using ``. These lines of code will not execute. | # print('Hello')
# the above code of line will not execute
# but the below one will
print('How are you?') | How are you?
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
You can also use `''' '''` for multi-line comments. | '''
Python is an important
programming language in
your Data Science journey
'''
print('Python') | Python
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
It's a good idea to write comments before your function explaining what that function does. Commenting out lines can also help debug your code. --- String conceptsStrings can be stored in variables. Variables are just placeholders for some value inside our code. | first_name = 'Pranav'
print(first_name) | Pranav
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Concatenate stringsYou can combine strings with the `+` operator. | first_name = 'John'
last_name = 'Doe'
print(first_name + last_name)
print('Hello, ' + first_name + ' ' + last_name) | JohnDoe
Hello, John Doe
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Functions to modify stringsBelow we have used functions to - convert a string to uppercase - convert a string to lowercase- capitalize just the first word- count all of the instances of a particular string. | sentence = 'My name is John Doe'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
print(sentence.count('o')) | MY NAME IS JOHN DOE
my name is john doe
My name is john doe
2
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
You can use the escape character (backslash) `\` to insert characters that are illegal in a string. An example of an illegal character is a single quote inside a string that is surrounded by single quotes. | first_name = input('What\'s your first name? ')
last_name = input('What\'s is your last name? ')
print('Hello, ' + first_name.capitalize() +
' ' + last_name.capitalize()) | What's your first name? JOHN
What's is your last name? doe
Hello, John Doe
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Custom string formattingTo infuse things in strings dynamically, you can use string formatting. | first_name = 'John'
last_name = 'Doe' | _____no_output_____ | MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
There are two ways you can do this:- formatting with `.format()` string method | name = 'Hello, {} {}'.format(first_name, last_name)
print(name) | Hello, John Doe
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
- formatting with string literals, called f-strings | name = f'Hello, {first_name} {last_name}'
print(name) | Hello, John Doe
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
--- Working with numbersNumbers can be stored in variables. Make sure the variables have meaningful names. We can pass those variables inside functions. | pi = 3.14159
print(pi) | 3.14159
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Math with Numbers- `+` for addition- `-` for subtraction- `*` for multiplication- `/` for division- `**` for exponent | num1 = 9
num2 = 5
print(num1 + num2)
print(num1 ** num2) | 14
59049
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Type ConversionYou cannot combine strings with numbers in Python. For e.g., executing the code below will result in an error: | days_in_Dec = 31
print(days_in_Dec + ' days in December') | _____no_output_____ | MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
When displaying a string that contains numbers, you must convert the numbers into strings. | days_in_Dec = 31
print(str(days_in_Dec) + ' days in December') | 31 days in December
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Numbers can be stored as strings. However, numbers stored as strings are treated as strings. | num1 = '10'
num2 = '20'
print(num1 + num2) | 1020
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Also, the input function always returns a string. | num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
print(num1 + num2) | Enter the first number: 35
Enter the second number: 75
3575
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
But here you can see that you have a number stored in a string. What if you want to treat it as a number and do math with it? You can do another data type conversion. The `int` function will convert it to a whole number, while the `float` function will convert it into a floating point number that might have decimal pl... | num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
print(int(num1) + int(num2))
print(float(num1) + float(num2)) | Enter the first number: 35
Enter the second number: 75
110
110.0
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
--- Working with DatesWe often need current date and time when logging errors and saving data. To get the current date and time, we need to use the `datetime` library. | from datetime import datetime
# the now function returns a datetime object
current_date = datetime.now()
print('Today is: ' + str(current_date)) | Today is: 2021-06-05 11:49:47.183898
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
There are a whole bunch of functions you can use with `datetime` objects to manipulate dates. `timedelta` is used to define a period of time. | from datetime import datetime, timedelta
today = datetime.now()
print('Today is: ' + str(today))
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)
yesterday = today - one_day
past_week = today - one_week
print('Yesterday was: ' + str(yesterday))
print('One week ago was: ' + str(past_week)) | Today is: 2021-06-05 12:01:31.236665
Yesterday was: 2021-06-04 12:01:31.236665
One week ago was: 2021-05-29 12:01:31.236665
| MIT | _jupyterNotebooks/python_tutorial/python_basics_1.ipynb | PranavShirole/PranavShirole.github.io |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.