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
Output Table:
orbit_df.head()
_____no_output_____
Apache-2.0
notebooks/Orbit Computation/Orbit Computation.ipynb
open-space-collective/open-space-toolk
2D plot, over **World Map**:
figure = go.Figure( data = go.Scattergeo( lon = orbit_df['$Longitude$'], lat = orbit_df['$Latitude$'], mode = 'lines', line = go.scattergeo.Line( width = 1, color = 'red' ) ), layout = go.Layout( title = None, showlegend = False...
_____no_output_____
Apache-2.0
notebooks/Orbit Computation/Orbit Computation.ipynb
open-space-collective/open-space-toolk
3D plot, in **Earth Fixed** frame:
figure = go.Figure( data = [ go.Scattergeo( lon = orbit_df['$Longitude$'], lat = orbit_df['$Latitude$'], mode = 'lines', line = go.scattergeo.Line( width = 2, color = 'rgb(255, 62, 79)' ) ) ], layout ...
_____no_output_____
Apache-2.0
notebooks/Orbit Computation/Orbit Computation.ipynb
open-space-collective/open-space-toolk
3D plot, in **Earth Inertial** frame:
theta = np.linspace(0, 2 * np.pi, 30) phi = np.linspace(0, np.pi, 30) theta_grid, phi_grid = np.meshgrid(theta, phi) r = float(Earth.equatorial_radius.in_meters()) x = r * np.cos(theta_grid) * np.sin(phi_grid) y = r * np.sin(theta_grid) * np.sin(phi_grid) z = r * np.cos(phi_grid) earth = go.Surface( x=x, y=...
_____no_output_____
Apache-2.0
notebooks/Orbit Computation/Orbit Computation.ipynb
open-space-collective/open-space-toolk
prepared by Maksim Dimitrijev (QLatvia) This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcommand{...
# # your solution is here #
_____no_output_____
Apache-2.0
silver/C05_Global_And_Local_Phase.ipynb
VGGatGitHub/QWorld-silver
Germany: LK Kitzingen (Bayern)* Homepage of project: https://oscovida.github.io* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Bayern-LK-Kitzingen.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(country="Germany", subregion="LK Kitzingen"); # load the data cases, deaths, re...
_____no_output_____
CC-BY-4.0
ipynb/Germany-Bayern-LK-Kitzingen.ipynb
RobertRosca/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/Germany-Bayern-LK-Kitzingen.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for...
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/Germany-Bayern-LK-Kitzingen.ipynb
RobertRosca/oscovida.github.io
test_str="xxup copy of course appear of course or half - dressed on his gf ill cross ! i was unemployed vans - land through the smallest shoes leave" for x in test_str.split(): print (f'{x}')
xxup copy of course appear of course or half - dressed on his gf ill cross ! i was unemployed vans - land through the smallest shoes leave
MIT
untoken.ipynb
gdoteof/DiscordChatExporter
xxup is a token which mean the next word should be uppercased.
pieces = test_str.split() for idx,val in enumerate(pieces): print(f'{idx}:{val}') def un_xxup(str): pieces = test_str.split() for index,value in enumerate(pieces): if value == 'xxup': pieces[index+1] = pieces[index+1].capitalize() del pieces[index] return " ".join(pieces) un_xxup(test_str)
_____no_output_____
MIT
untoken.ipynb
gdoteof/DiscordChatExporter
TD1: Timeseries analysis using autoregressive methods and general Box-Jenkins methodsSome useful translations, just in case:- **a timeseries**: une série temporelle (always plural in English)- **a trend**: une tendance- **a lag**: un retard, un décalage dans le temps- **stationary**: stationnaireSome interesting cont...
!pip install statsmodels==0.12.1 !pip install sktime import requests import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels import sktime import scipy
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
1. AnalysisFor this exercise, we will use a timeseries representing daily average temperature in Melbourne, Australia between 1980 and 1990.This timeseries will be stored in a [Pandas DataFrame object](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html), a standard to handle tabular data ...
# Read data from remote repository df = pd.read_csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv", index_col=0) # Display the 5 first data points df.head()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
1.1 Run-plots analysis"Run-plots" are the simplest representation of a timeseries, where the x-axis represents time and the y-axis represents the observed variable, here temperature in Celsius degrees.**Question: Given the figures and the statistic test below, what hypothesis can you draw regarding the behaviour of th...
# Plot the full timeseries df.plot(figsize=(20, 4), title="Temperature in Melbourne - 1980 to 1990") # Plot the first year of data df.iloc[:365].plot(figsize=(20, 4), title="Temperature in Melbourne - one year")
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
The Augmented Dickey-Fuller test is a statistical test used to checkthe stationarity of a timeseries. It is implemented in the `adfuller()` function in `statsmodels`.
from statsmodels.tsa.stattools import adfuller adf, p, *other_stuff = adfuller(df) print(f"p-value (95% confidence interval): {p:g}, statistics: {adf:g}")
p-value (95% confidence interval): 0.000247083, statistics: -4.4448
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
1.2 Autocorrelation and partial autocorrelationAutocorrelation (and partial autocorrelation) are metrics that can be computed to evaluate **how dependent the variable is from its $n$ previous values**, what is called a **lag (of length n)**.**Question: Plot $X[t-1]$ versus $X[t]$, for all $t$. What can you conclude on...
# Create a shifted version of the timeseries: df_shifted = df.shift(periods=1) # Plot df vs. df_shifted plt.figure(figsize=(5, 5)) plt.scatter(df, df_shifted) plt.xlabel("X[t]") plt.ylabel("X[t-1]") plt.show()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
It seems to be like X[t] timeseries explains globaly the X[t-1] timeseries because the graph above is quite like a linear graph. But in middle of the graph, the line is very thick so it's difficult to explain the X[t-1] by the X[t] value. ~ not high correlated **Pearson correlation coefficient**To compute this coeffic...
# Plot of the distribution of the variable # (in our case, the temperature histogram) df.hist() # The hist graph seems to be an normal dist hist with a ~ mean of 12 from scipy import stats # Normality test k2, p = scipy.stats.normaltest(df) print(f"p-value (95% confidence interval): {p[0]:g}, statistics: {k2[0]:g}")...
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
We can see that the value has a quite normal distribution so we can calculate the Pearson Correlation Value. The correlation between X[t-1] and X[t] is 0.77 (~ close to 1) so the two var are very correlated. We probably explain X[t] by X[t-1]. ---We will now compute autocorrelation function (ACF) and partial autocorrel...
from statsmodels.graphics.tsaplots import plot_pacf, plot_acf
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
1.2.1 Autocorrelation
# Plot autocorrelation for lags between 1 and 730 days plot_acf(df.values.squeeze(), lags=730) plt.show() # Plot autocorrelation for lags between 1 and 31 days plot_acf(df.values.squeeze(), lags=31) plt.show()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
1.2.2 Partial autocorrelation
# Plot partial autocorrelation for lags between 1 and 730 days plot_pacf(df.values.squeeze(), lags=730) plt.show() # Plot partial autocorrelation for lags between 1 and 31 days plot_pacf(df.values, lags=31) plt.show()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
The correlation seem to be the strongest with a lag which is a multiple of 180.2 (1/2 year), but verry bad monthly or with any other lag. 2. Modeling 2.0 Modeling: AR from scratch (just as an example, nothing to do here)AR stands for AutoRegressive. Autoregressive models describe the value of any points in a timeseri...
# We store all values of the series in a numpy array called series series = df["Temp"].values def auto_regression(series, order): n_points = len(series) # All lagged values will be stored in y_lag. # If order is 7, for each timestep we will store 7 values. X_lag = np.zeros((order, n_points-order))...
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
Now that we have our coefficients learned, we can make predictions.
lag = beta.shape[1] Y_truth = [] # real timeseries Y_pred = [] # predictions for i in range(0, len(series)-lag-1): # apply the equation of AR using the coefficients at each time steps y = alpha + np.dot(beta, series[i:i+lag]) # y[t] = alpha + y[t-1]*beta1 + y[t-2]*beta2 + ... Y_pred.append(y) Y_tru...
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
And here are our coefficients:
coefs = np.c_[alpha, beta] plt.bar(np.arange(coefs.shape[1]), coefs.flatten()) labels = ['$\\alpha$'] for i in range(beta.shape[1]): labels.append(f"$\\beta_{i+1}$") plt.xticks(np.arange(coefs.shape[1]), labels) plt.show()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
2.1 Modeling : ARIMA
from statsmodels.tsa.arima.model import ARIMA
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
ARIMA is an acronym that stands for AutoRegressive Integrated Moving Average, capturing the key aspects of the model :- **AR** : *AutoRegressive* A model that uses the dependent relationship between an observation and some number of lagged observations.A pure AR model is such that :$$Y_t = \alpha + \beta_1 Y_{t-1} + \b...
# seasonal difference differenced = df.diff(365) # trim off the first year of empty data differenced = differenced[365:] # Create an ARIMA model (check the statsmodels docs) (p,d,q) # d = 0 because the serie is stationary (see before) model = ARIMA(series, order=(3, 0, 15)) # fit model model_fit = model.fit() print(m...
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
To evaluate the ARIMA model, we will use walk forward validation. First we split the data into a training and testing set (initially, a year is a good interval to test for this dataset given the seasonal nature). A model will be constructed on the historic data and predict the next time step. The real observation of th...
from math import sqrt from sklearn.metrics import mean_squared_error # rolling forecast with ARIMA train, test = differenced.iloc[:-365], differenced.iloc[-365:] # walk-forward validation values = train.values history = [v for v in values] predictions = list() test_values = test.values for t in range(len(test_values...
RSME : 3.0962731960398195
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
We can also use the predict() function on the results object to make predictions. It accepts the index of the time steps to make predictions as arguments. These indexes are relative to the start of the training dataset.
forecast = model_fit.predict(start=len(train.values), end=len(differenced.values), typ='levels') plt.plot(test) plt.plot(forecast, color='red') plt.show()
_____no_output_____
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
Exercise: Mauna Loa CO2 concentration levels (1975 - 2021)Carbon dioxyde (CO2) is a gas naturaly present in our environment. However, the concentration of CO2 is increasing every year, mainly because of human activities. It is one of the major cause of global warming, and its value is precautiounously measured since 1...
ts = pd.read_csv("https://gml.noaa.gov/aftp/data/trace_gases/co2/in-situ/surface/mlo/co2_mlo_surface-insitu_1_ccgg_MonthlyData.txt", header=150, sep=" ") ts = ts[ts["year"] > 1975] time_index = pd.DatetimeIndex(pd.to_datetime(ts[["year", "month", "day"]])) ts = ts.set_index(time_index) ts = pd.Series...
p-value (95% confidence interval): 5.4641e-36, statistics: 162.39
CC0-1.0
TD1_Timeseries_Analysis.ipynb
RomainBnfn/Timeseries-Sequence-Processing-2021
🍔 K Means Clustering Step By Step Installation
# remove `!` if running the line in a terminal !pip install -U RelevanceAI[notebook]==2.0.0
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Setup First, you need to set up a client object to interact with RelevanceAI.
from relevanceai import Client client = Client()
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Data You will need to have a dataset under your Relevance AI account. You can either use our e-commerce dataset as shown below or follow the tutorial on how to create your own dataset.Our e-commerce dataset includes fields such as `product_title`, as well as the vectorized version of the field `product_title_clip_vect...
from relevanceai.utils.datasets import get_ecommerce_dataset_encoded documents = get_ecommerce_dataset_encoded() {k: v for k, v in documents[0].items() if "_vector_" not in k}
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Upload the data to Relevance AI Run the following cell, to upload these documents into your personal Relevance AI account under the name `quickstart_clustering_kmeans`
ds = client.Dataset("quickstart_kmeans_clustering") ds.insert_documents(documents)
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Check the data
ds.health() ds.schema
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Clustering We apply the Kmeams clustering algorithm to the vector field, `product_title_clip_vector_`
from sklearn.cluster import KMeans VECTOR_FIELD = "product_title_clip_vector_" KMEAN_NUMBER_OF_CLUSTERS = 5 ALIAS = "kmeans_" + str(KMEAN_NUMBER_OF_CLUSTERS) model = KMeans(n_clusters=KMEAN_NUMBER_OF_CLUSTERS) clusterer = client.ClusterOps(alias=ALIAS, model=model) clusterer.run( dataset_id="quickstart_kmeans_clu...
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
We download a small sample and show the clustering results using our json_shower.
from relevanceai import show_json sample_documents = ds.sample(n=5) samples = [ { "product_title": d["product_title"], "cluster": d["_cluster_"][VECTOR_FIELD][ALIAS], } for d in sample_documents ] show_json(samples, text_fields=["product_title", "cluster"])
_____no_output_____
Apache-2.0
guides/kmeans_clustering_step_by_step_guide.ipynb
RelevanceAI/RelevanceAI
Image Manipulation with skimage This example builds a simple UI for performing basic image manipulation with [scikit-image](http://scikit-image.org/).
# Stdlib imports from io import BytesIO # Third-party libraries from IPython.display import Image from ipywidgets import interact, interactive, fixed import matplotlib as mpl from skimage import data, filters, io, img_as_float import numpy as np
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
Let's load an image from scikit-image's collection, stored in the `data` module. These come back as regular numpy arrays:
i = img_as_float(data.coffee()) i.shape
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
Let's make a little utility function for displaying Numpy arrays with the IPython display protocol:
def arr2img(arr): """Display a 2- or 3-d numpy array as an image.""" if arr.ndim == 2: format, cmap = 'png', mpl.cm.gray elif arr.ndim == 3: format, cmap = 'jpg', None else: raise ValueError("Only 2- or 3-d arrays can be displayed as images.") # Don't let matplotlib autoscale...
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
Now, let's create a simple "image editor" function, that allows us to blur the image or change its color balance:
def edit_image(image, sigma=0.1, R=1.0, G=1.0, B=1.0): new_image = filters.gaussian(image, sigma=sigma, multichannel=True) new_image[:,:,0] = R*new_image[:,:,0] new_image[:,:,1] = G*new_image[:,:,1] new_image[:,:,2] = B*new_image[:,:,2] return arr2img(new_image)
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
We can call this function manually and get a new image. For example, let's do a little blurring and remove all the red from the image:
edit_image(i, sigma=5, R=0.1)
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
But it's a lot easier to explore what this function does by controlling each parameter interactively and getting immediate visual feedback. IPython's `ipywidgets` package lets us do that with a minimal amount of code:
lims = (0.0,1.0,0.01) interact(edit_image, image=fixed(i), sigma=(0.0,10.0,0.1), R=lims, G=lims, B=lims);
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
Browsing the scikit-image gallery, and editing grayscale and jpg imagesThe coffee cup isn't the only image that ships with scikit-image, the `data` module has others. Let's make a quick interactive explorer for this:
def choose_img(name): # Let's store the result in the global `img` that we can then use in our image editor below global img img = getattr(data, name)() return arr2img(img) # Skip 'load' and 'lena', two functions that don't actually return images interact(choose_img, name=sorted(set(data.__all__)-{'len...
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
And now, let's update our editor to cope correctly with grayscale and color images, since some images in the scikit-image collection are grayscale. For these, we ignore the red (R) and blue (B) channels, and treat 'G' as 'Grayscale':
lims = (0.0, 1.0, 0.01) def edit_image(image, sigma, R, G, B): new_image = filters.gaussian(image, sigma=sigma, multichannel=True) if new_image.ndim == 3: new_image[:,:,0] = R*new_image[:,:,0] new_image[:,:,1] = G*new_image[:,:,1] new_image[:,:,2] = B*new_image[:,:,2] else: ...
_____no_output_____
BSD-3-Clause
docs/source/examples/Image Processing.ipynb
akhand1111/ipywidgets
Compare phase estimation methods on hippocampal theta oscillations
import numpy as np import scipy as sp %matplotlib notebook %config InlineBackend.figure_format = 'retina' %matplotlib inline import matplotlib.pyplot as plt
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Load data
x = np.load('/gh/data2/hc3/npy/gor01/2006-6-7_16-40-19/10/lfp_0.npy') x = x[10000:30000] Fs = 1252
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Preprocess data
cflow = 50 Ntapslow = 501 cfhigh = 1 Ntapshigh = 1001 from misshapen import nonshape x = nonshape.highpass_default(x, Fs, cfhigh, Ntapshigh) x = nonshape.lowpass_default(x, Fs, cflow, Ntapslow)
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Compute phase time series Bandpass + hilbert
f_range = (4,10) x_filt, _ = nonshape.bandpass_default(x, f_range, Fs, rmv_edge=False) pha_h = np.angle(sp.signal.hilbert(x_filt))
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Peak and trough interpolation
Ps, Ts = nonshape.findpt(x, f_range, Fs) pha_pt = nonshape.wfpha(x, Ps, Ts)
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Compare phase time series
t = np.arange(0,len(x)/Fs, 1/Fs) tlims = [1,3] samps = np.logical_and(t>=tlims[0],t<tlims[1]) plt.figure(figsize=(16,6)) plt.subplot(2,1,1) plt.plot(t[samps],x[samps],'k') plt.xlim(tlims) plt.ylabel('Voltage (uV)',size=20) plt.subplot(2,1,2) plt.plot(t[samps],pha_h[samps],'r',label='Hilbert') plt.plot(t[samps],pha_pt[...
_____no_output_____
MIT
misc/.ipynb_checkpoints/Theta phase estimate-checkpoint.ipynb
srcole/qwm
Downloading data dynamically
# Required libraries import os import tarfile import urllib # DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/" DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml/master/" # HOUSING_PATH = os.path.join('datasets', 'housing') HOUSING_PATH = '../Datasets' HOUSING_URL = DOWNL...
1 2 3 *File downloaded and extracted successfully*
MIT
Projects/Housing/Code/Housing data download.ipynb
drnesr/Machine_Learning
Load dataset:MNIST and CIFAR10
mnist = fetch_openml("mnist_784") mnist.data.shape print('Data: {}, target: {}'.format(mnist.data.shape, mnist.target.shape)) X_train, X_test, y_train, y_test = train_test_split( mnist.data, mnist.target, test_size=1/7, random_state=0, ) X_train = X_train.values.reshape((len(X_train), 784)) X_test = X...
_____no_output_____
MIT
PSForest_example.ipynb
nishiwen1214/PSForest
Using the PSForest
start =time.clock() before_mem = memory_profiler.memory_usage() # Create PSForest model ps_forest = PSForest( estimators_config={ 'mgs': [{ 'estimator_class': RandomForestClassifier, 'estimator_params': { 'n_estimators': 500, 'max_features': 1, ...
accuracy: 0.896
MIT
PSForest_example.ipynb
nishiwen1214/PSForest
Optional side-effect
val nameOpt = Option("Amir") def printName(name: String) = println(name) nameOpt.foreach(printName) val anotherOpt = None anotherOpt.foreach(printName)
_____no_output_____
MIT
scala/Optional side-effect.ipynb
ashishpatel26/learning
Agenda- Why Logging- How does Logging work for you?- Optional Content The Presentation- The slides, support code and jypyter notebook are on Github- [https://github.com/stbaercom/europython2015_logging](https://github.com/stbaercom/europython2015_logging) A Simple Program, Without any Logging
from datetime import datetime def my_division_p(dividend, divisor): try: print("Debug, Division : {}/{}".format(dividend,divisor)) result = dividend / divisor return result except (ZeroDivisionError, TypeError): print("Error, Division Failed") return None def division_ta...
_____no_output_____
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Let us Have a Look at the Output
task = [(3,4),(5,1.4),(2,0),(3,5),("10",1)] division_task_handler_p(task)
Handling division task,5 items Doing devision iteration 0 on 2015 Debug, Division : 3/4 Doing devision iteration 1 on 2015 Debug, Division : 5/1.4 Doing devision iteration 2 on 2015 Debug, Division : 2/0 Error, Division Failed Doing devision iteration 3 on 2015 Debug, Division : 3/5 Doing devision iteration 4 on 2015 D...
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
The Problems with ``print()``- We don't have a way to select the types of messages we are interested in- We have to add all information (timestamps, etc...) by ourselves- All our messages will look slightly different- We have only limited control where our message end up What is Different with Logging?- We have more...
import log1; logging = log1.get_clean_logging() logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() def my_division(dividend, divisor): try: log.debug("Division : %s/%s", dividend, divisor) result = dividend / divisor return result except (ZeroDivisionError, TypeError): ...
_____no_output_____
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
The Call and the Log Messages
task = [(3,4),(2,0),(3,5),("10",1)] division_task_handler(task)
INFO:root:Handling division task,4 items INFO:root:Doing devision iteration 0 DEBUG:root:Division : 3/4 INFO:root:Doing devision iteration 1 DEBUG:root:Division : 2/0 ERROR:root:Error, Division Failed Traceback (most recent call last): File "<ipython-input-10-a904db1e3e23>", line 8, in my_division result = divide...
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
How does the Logging Module represent these Aspect Back to Code. How does Logging Work?
import log1;logging = log1.get_clean_logging() # this would be import logging outside this notebook logging.debug("Find me in the log") logging.info("I am hidden") logging.warn("I am here") logging.error("As am I") try: 1/0; except: logging.exception(" And I") logging.critical("Me, of course")
WARNING:root:I am here ERROR:root:As am I ERROR:root: And I Traceback (most recent call last): File "<ipython-input-12-75f8227eec02>", line 8, in <module> 1/0; ZeroDivisionError: division by zero CRITICAL:root:Me, of course
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
More Complex Logging Setup with ``basicConfig()``
import log1;logging = log1.get_clean_logging() datefmt = "%Y-%m-%d %H:%M:%S" msgfmt = "%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s" logging.basicConfig(level=logging.DEBUG, format=msgfmt, datefmt=datefmt) logging.debug("Now I show up ") logging.info("Now this is %s logging!","good") logging.warn...
2015-07-19 20:19:55,551 DEBUG root : Now I show up 2015-07-19 20:19:55,552 INFO root : Now this is good logging! 2015-07-19 20:19:55,552 WARNING root : I am here. 1 + 3 = 4 2015-07-19 20:19:55,552 ERROR root : As am I 2015-07-19 20:19:55,553 ERROR ...
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Some (personal) Remarks about ``basicConfig()``- `basicConfig()` does save you some typing, but I would go for the 'normal' setup. - Using `basicConfig()` is a matter of personal taste.- The normal setup makes the structure clearer.- Keep in mind that basicConfig() is meant to be called once... Using the Standard Co...
import log1, json, logging.config;logging = log1.get_clean_logging() datefmt = "%Y-%m-%d %H:%M:%S" msgfmt = "%(asctime)s,%(msecs)03d %(levelname)-6s %(name)-10s : %(message)s" log = logging.getLogger() log.setLevel(logging.DEBUG) lh = logging.StreamHandler() lf = logging.Formatter(fmt=msgfmt, datefmt=datefmt) lh.se...
2015-07-19 20:19:55,571 INFO root : Now this is good logging! 2015-07-19 20:19:55,572 DEBUG root : A slightly more complex message 1 + 2 = 3
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Now, back to the Theory. What have we Build? How do we get from the Configuration to the Log Message? Formatting : Attributes Available for the Logging Call AttributeDescriptionargsTuple of arguments passed to the logging callasctimeLog record creation time, formattedcreatedLog record creation time, seconds since t...
import log1, json, logging.config;logging = log1.get_clean_logging() conf_dict = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'longformat': { 'format': "%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S"}}...
2015-07-19 20:19:55,602 INFO root : Now this is good logging!
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Adding a ``Filehandler`` to the Logger
import log1, json, logging.config;logging = log1.get_clean_logging() base_config = json.load(open("conf_dict.json")) base_config['handlers']['logfile'] = { 'class' : 'logging.FileHandler', 'mode' : 'w', 'filename' : 'logfile.txt', 'formatter': "longformat"} base_config['loggers']['']['handlers'].appen...
2015-07-19 20:19:55,618 INFO root : Now this is good logging!
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Another look at the logging object tree Set the Level on the ``FileHandler``
import log1, json, logging.config;logging = log1.get_clean_logging() file_config = json.load(open("conf_dict_with_file.json")) file_config['handlers']['logfile']['level'] = "WARN" logging.config.dictConfig(file_config) log = logging.getLogger() log.info("Now this is %s logging!","good") log.warning("Now this is %s l...
2015-07-20 19:04:03,132 INFO root : Now this is good logging! 2015-07-20 19:04:03,133 WARNING root : Now this is worrisome logging!
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Adding Child Loggers under the Root
import log1,json,logging.config;logging = log1.get_clean_logging() logging.config.dictConfig(json.load(open("conf_dict.json"))) log = logging.getLogger("") child_A = logging.getLogger("A") child_B = logging.getLogger("B") child_B_A = logging.getLogger("B.A") log.info("Now this is %s logging!","good") child_A.info("...
2015-07-19 20:19:55,865 INFO root : Now this is good logging! 2015-07-19 20:19:55,866 INFO A : Now this is more logging! 2015-07-19 20:19:55,867 WARNING root : Now this is worrisome logging!
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Looking at the tree of Logging Objects Best Practices for the Logging Tree- Use ``.getLogger(__name__)`` per module to define loggers under the root logger- Set propagate to True on each Logger- Attach Handlers and Filters as needed to control output from the Logging hierarchy Filter - Now that things are Getting C...
import log1,json,logging.config;logging = log1.get_clean_logging() logging.config.dictConfig(json.load(open("conf_dict.json"))) def log_filter(rec): # Callables work with 3.2 and later if 'please' in rec.msg.lower(): return True return False log = logging.getLogger("") log.addFilter(log_filter) child...
2015-07-20 08:01:55,108 INFO A : Just log me 2015-07-20 08:01:55,108 INFO root : Hallo, Please log me
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
The Way of a Logging Record A second Example for Filters, in the LogHandler
import log1, json, logging.config;logging = log1.get_clean_logging() datefmt = "%Y-%m-%d %H:%M:%S" msgfmt = "%(asctime)s,%(msecs)03d %(levelname)-6s %(name)-10s : %(message)s" log_reg = None def handler_filter(rec): # Callables work with 3.2 and later global log_reg if 'please' in rec.msg.lower(): rec....
2015-07-19 20:19:55,905 WARNING root : Hi, I am LOGGY. I am 11 seconds old. Please log me (I am nice)
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Things you might want to know ( if we still have some time) A short look at our LogRecord
print(log_reg) log_reg.__dict__
<LogRecord: root, 30, <ipython-input-20-d1d101ab918f>, 25, "Hi, I am %s. I am %i seconds old. Please log me (I am nice)">
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Logging Performance - Slow, but Fast EnoughScenario (10000 Call, 3 Logs per call)RuntimeFull Logging with buffered writes3.096sDisable Caller information2.868sCheck Logging Lvl before Call, Logging disabled0.186sLogging module level disabled0.181sNo Logging calls at all0.157s Getting the current Logging Tree
import json, logging.config config = json.load(open("conf_dict_with_file.json")) logging.config.dictConfig(config) import requests import logging_tree logging_tree.printout()
<--"" Level DEBUG Handler Stream <IPython.kernel.zmq.iostream.OutStream object at 0x105d043c8> Formatter fmt='%(asctime)s,%(msecs)03d %(levelname)-10s %(name)-15s : %(message)s' datefmt='%Y-%m-%d %H:%M:%S' Handler File '/Users/imhiro/AllFiles/0021_travel_events_conferences_workshops/2015-07-19_europython/...
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Reconfiguration- It is possible to change the logging configuration at runtime- It is even part of the standard library- Still, some caution is in order Reloading the configuration _can_ disable the existing loggers
import log1,json,logging,logging.config;logging = log1.get_clean_logging() #Load Config, define a child logger (could also be a module) logging.config.dictConfig(json.load(open("conf_dict_with_file.json"))) child_log = logging.getLogger("somewhere") #Reload Config logging.config.dictConfig(json.load(open("conf_dict...
_____no_output_____
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Reloading can happen in place
import log1, json, logging, logging.config;logging = log1.get_clean_logging() config = json.load(open("conf_dict_with_file.json")) #Load Config, define a child logger (could also be a module) logging.config.dictConfig(config) child_log = logging.getLogger("somewhere") config['disable_existing_loggers'] = False #Rel...
2015-07-19 20:20:42,290 INFO somewhere : Now this is good logging!
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
Successful Logging to all of You
from presentation_helper import customize_settings customize_settings()
_____no_output_____
MIT
europython_2015_logging_talk.ipynb
stbaercom/europython2015_logging
%%capture pip install arviz import numpy as np import pymc3 as pm import theano.tensor as tt import arviz as az import matplotlib.pyplot as plt import seaborn as sns
_____no_output_____
MIT
ThinkBayes_Chapter_9.ipynb
ricardoV94/ThinkBayesPymc3
9.1 Paintball
def StrafingSpeed(alpha, beta, x): theta = tt.arctan2(x-alpha, beta) speed = beta / tt.cos(theta)**2 return speed with pm.Model() as m_9_3: obs_beta = pm.Data('obs_beta', [10]) alpha = pm.Uniform('alpha', lower=0, upper=31, observed=10) beta = pm.Uniform('beta', lower=1, upper=51, observed=obs...
_____no_output_____
MIT
ThinkBayes_Chapter_9.ipynb
ricardoV94/ThinkBayesPymc3
9.5 Joint distributionsResults are very different from those of the book. Posterior is much more narrow.
with pm.Model() as m_9_5: alpha = pm.Uniform('alpha', lower=0, upper=31) beta = pm.Uniform('beta', lower=1, upper=51) location = pm.Uniform('location', lower=0, upper=31, observed=[15, 16, 18, 21]) speed = pm.Deterministic('speed', StrafingSpeed(alpha, beta, location)) like = pm.Potential('like', ...
_____no_output_____
MIT
ThinkBayes_Chapter_9.ipynb
ricardoV94/ThinkBayesPymc3
9.6 Conditional Distributions
with pm.Model() as m_9_6: obs_beta = pm.Data('obs_beta', 10) alpha = pm.Uniform('alpha', lower=0, upper=31) beta = pm.Uniform('beta', lower=1, upper=51, observed=obs_beta) location = pm.Uniform('location', lower=0, upper=31, observed=[15, 16, 18, 21]) speed = pm.Deterministic('speed', StrafingSpe...
_____no_output_____
MIT
ThinkBayes_Chapter_9.ipynb
ricardoV94/ThinkBayesPymc3
Multiple Linear Regression
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split diabetes = datasets.load_diabetes() #load dataset diabetes_X = diabetes.data X_train, X_test, y_train, y_test = tra...
Coefficients: [[ 37.90031426 -241.96624835 542.42575342 347.70830529 -931.46126093 518.04405547 163.40353476 275.31003837 736.18909839 48.67112488]] Mean squared error: 2900.17 Variance score: 0.45
MIT
Module 4/multilinear_regression.ipynb
axel-sirota/interpreting-data-with-advanced-models
Handling missing values
# get the number of missing data points per column missing_values_count = nfl_data.isnull().sum() # how many total missing values do we have? total_cells = np.product(nfl_data.shape) total_missing = missing_values_count.sum() # percent of data that is missing percent_missing = (total_missing/total_cells) * 100 print(...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Scaling and normalization
# for Box-Cox Transformation from scipy import stats # for min_max scaling from mlxtend.preprocessing import minmax_scaling # set seed for reproducibility np.random.seed(0)
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
In scaling, you're changing the range of your data
# generate 1000 data points randomly drawn from an exponential distribution original_data = np.random.exponential(size=1000) # mix-max scale the data between 0 and 1 scaled_data = minmax_scaling(original_data, columns=[0]) # plot both together to compare fig, ax = plt.subplots(1,2) sns.distplot(original_data, ax=ax[0...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
In normalization, you're changing the shape of the distribution of your data.
# normalize the exponential data with boxcox normalized_data = stats.boxcox(original_data)
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Parsing Dates - it will be "object" if you don't parse it.
import datetime
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
if a date is MM/DD/YY (02/25/17) the format is "%m/%d/%y""%Y" (upper y) is used if the year has four digits (2017)That is (02/25/2017) the format is "%m/%d/%Y"Other formats: DD/MM/YY (25/02/17 - "%d/%m/%y") ; DD-MM-YY (25-02-17 - "%d-%m-%y"). At the end, the date will be show as the defaut YYYY-MM-DD (datetime64)
# create a new column, date_parsed, with the parsed dates landslides['date_parsed'] = pd.to_datetime(landslides['date'], format="%m/%d/%y")
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
If your dates is with multiple formats, you can use "infer_datetime_format".
landslides['date_parsed'] = pd.to_datetime(landslides['Date'], infer_datetime_format=True) day_of_month_landslides = landslides['date_parsed'].dt.day
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
To check if everything looks right
date_lengths = earthquakes.Date.str.len() date_lengths.value_counts() #or showing trhough a histogram of the day (values must be in [0,31] ) #In that example, 3 dates have len of 24. So we run this code indices = np.where([date_lengths == 24])[1] print('Indices with corrupted data:', indices) earthquakes.loc[indices] ...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Character Encodings
# helpful character encoding module import chardet # look at the first ten thousand bytes to guess the character encoding with open("../input/kickstarter-projects/ks-projects-201801.csv", 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) # check what the character encoding might be print(result) # rea...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Exercises
#1 - class bytes We need to create a new_entry in bytes (UTF-8is defaut) sample_entry = b'\xa7A\xa6n' print(sample_entry) print('data type:', type(sample_entry)) #solution - Try using .decode() to get the string, then .encode() to get the bytes representation, encoded in UTF-8. before = sample_entry.decode("big5-tw") n...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Inconsistent Data
# helpful modules import fuzzywuzzy from fuzzywuzzy import process import chardet # get the top 10 closest matches to "south korea" # The closer str has ratio of 100 matches = fuzzywuzzy.process.extract("south korea", countries, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) # function to replace rows in the provid...
_____no_output_____
MIT
Data_Cleaning.ipynb
duartele/exerc-jupyternotebook
Scraping Fantasy Football Data (Week 3 Projections/Week 2 Actuals)Need to scrape the following data:- Weekly Player PPR Projections: ESPN, CBS, Fantasy Sharks, Scout Fantasy Sporsts, (and tried Fantasy Football Today but doesn't have defense projections currently, so exclude)- Previous Week Player Actual PPR Results-...
import pandas as pd import numpy as np import requests # import json # from bs4 import BeautifulSoup import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # from se...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get Weekly Player Actual Fantasy PPR PointsGet from ESPN's Scoring Leaders tablehttp://games.espn.com/ffl/leaders?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0- scoringPeriodId = week of the season- seasonId = year- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16- leag...
##SCRAPE ESPN SCORING LEADERS TABLE FOR ACTUAL FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_actual_PPR_player_points_ESPN(week, year): #instantiate the driver driver = instantiate_selenium_driver() #initialize dataf...
Pickle saved to: pickle_archive/Week2_Player_Actual_PPR_messy_scrape_2018-9-18-17-59.pkl Pickle saved to: pickle_archive/Week2_Player_Actual_PPR_2018-9-18-17-59.pkl (1009, 5)
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get ESPN Player Fantasy Points Projections for Week Get from ESPN's Projections Tablehttp://games.espn.com/ffl/tools/projections?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0- scoringPeriodId = week of the season- seasonId = year- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, ...
##SCRAPE ESPN PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_ESPN(week, year): #instantiate the driver on the ESPN projections page driver = instantiate_selenium_driver...
Pickle saved to: pickle_archive/Week2_PPR_Projections_ESPN_messy_scrape_2018-9-18-18-3.pkl Pickle saved to: pickle_archive/Week3_PPR_Projections_ESPN_2018-9-18-18-3.pkl (1009, 5)
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get CBS Player Fantasy Points Projections for Week Get from CBS's Projections Tablehttps://www.cbssports.com/fantasy/football/stats/sortable/points/QB/ppr/projections/2018/2?&print_rows=9999- QB is where position goes- 2018 is where season goes- 2 is where week goes- print_rows = 9999 gives all results in one table
##SCRAPE CBS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_CBS(week, year): ###GET PROJECTIONS FROM CBS### #CBS has separate tables for each position, so need to cycle...
Pickle saved to: pickle_archive/Week3_PPR_Projections_CBS_messy_scrape_2018-9-18-18-4.pkl Pickle saved to: pickle_archive/Week3_PPR_Projections_CBS_2018-9-18-18-4.pkl (830, 5)
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get Fantasy Sharks Player Points Projection for WeekThey have a json option that gets updated weekly (don't appear to store previous week projections). The json defaults to PPR (which is lucky for us) and has an all players option.https://www.fantasysharks.com/apps/Projections/WeeklyProjections.php?pos=ALL&format=jso...
##SCRAPE FANTASY SHARKS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be week as number (year isn't used, but keep same format as others) #returns dataframe of scraped data def scrape_weekly_player_projections_Sharks(week, year): #fantasy sharks url - segment for 2018 week 1 starts at 628 an...
Pickle saved to: pickle_archive/Week3_PPR_Projections_Sharks_messy_scrape_2018-9-18-18-4.pkl Pickle saved to: pickle_archive/Week3_PPR_Projections_Sharks_2018-9-18-18-4.pkl (971, 5)
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get Scout Fantasy Sports Player Fantasy Points Projections for Week Get from Scout Fantasy Sports Projections Tablehttps://fftoolbox.scoutfantasysports.com/football/rankings/?pos=rb&week=2&noppr=false- pos is position with options of 'QB','RB','WR','TE', 'K', 'DEF'- week is week of year- noppr is set to false when you...
##SCRAPE Scout PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_SCOUT(week, year): ###GET PROJECTIONS FROM SCOUT### #SCOUT has separate tables for each position, so need ...
C:\Users\micha\Anaconda3\envs\PythonData\lib\site-packages\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) C:\Users...
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Get FanDuel Player Salaries for Week just import the Thurs-Mon game salaries (they differ for each game type, and note they don't include Kickers in the Thurs-Mon)Go to a FanDuel Thurs-Mon competition and Download a csv of players, which we then upload and format in python.
###FORMAT/EXTRACT FANDUEL SALARY INFO### def format_extract_FanDuel(df_fanduel_csv, week, year): #rename columns df_fanduel_csv.rename(columns={'Position':'POS', 'Nickname':'PLAYER', 'Team':'TEAM', 'Sala...
Pickle saved to: pickle_archive/Week3_Salary_FanDuel_2018-9-18-18-5.pkl (665, 5)
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
!!!FFtoday apparently doesn't do weekly projections for Defenses, so don't use it for now (can check back in future and see if updated)!!! Get FFtoday Player Fantasy Points Projections for Week Get from FFtoday's Projections Tablehttp://www.fftoday.com/rankings/playerwkproj.php?Season=2018&GameWeek=2&PosID=10&LeagueID...
# ##SCRAPE FFtoday PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## # #input needs to be year as four digit number and week as number # #returns dataframe of scraped data # def scrape_weekly_player_projections_FFtoday(week, year): # #instantiate selenium driver # driver = instantiate_selenium_driver() ...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Initial Database Stuff
# actual_ppr_df = pd.read_pickle('pickle_archive/Week1_Player_Actual_PPR_2018-9-13-6-41.pkl') # espn_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_ESPN_2018-9-13-6-46.pkl') # cbs_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_CBS_2018-9-13-17-45.pkl') # cbs_final_df.head() # from sqla...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL-Week3.ipynb
zgscherrer/Project-Fantasy-Football
Basics of CodingIn this chapter, you'll learn about the basics of objects, types, operations, conditions, loops, functions, and imports. These are the basic building blocks of almost all programming languages.This chapter has benefited from the excellent [*Python Programming for Data Science*](https://www.tomasbeuzen....
a = 10 print(a)
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists
This creates a variable `a`, assigns the value 10 to it, and prints it. Sometimes you will hear variables referred to as *objects*. Everything that is not a literal value, such as `10`, is an object. In the above example, `a` is an object that has been assigned the value `10`.How about this:
b = "This is a string" print(b)
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists
It's the same thing but with a different **type** of data, a string instead of an integer. Python is *dynamically typed*, which means it will guess what type of variable you're creating as you create it. This has pros and cons, with the main pro being that it makes for more concise code.```{admonition} ImportantEveryth...
list_example = [10, 1.23, "like this", True, None] print(list_example)
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists
is completely valid code. `None` is a special type of nothingness, and represents an object with no value. It has type `NoneType` and is more useful than you might think! As well as the built-in types, packages can define their own custom types. If you ever want to check the type of a Python variable, you can call the ...
type(list_example)
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists
This is especially useful for debugging `ValueError` messages.Below is a table of common data types in Python:| Name | Type name | Type Category | Description | Example || :-------------------- | :--------- | :------------- | :-------------...
list_example.append("one more entry") print(list_example)
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists
And you can access earlier entries using an index, which begins at 0 and ends at one less than the length of the list (this is the convention in many programming languages). For instance, to print specific entries at the start, using `0`, and end, using `-1`:
print(list_example[0]) print(list_example[-1])
_____no_output_____
MIT
code-basics.ipynb
lukestein/coding-for-economists