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 |
|---|---|---|---|---|---|
9.2. Cluster Profile |
df92 = df4[cols_selected].copy()
df92['cluster']= labels
# Number of customer
df_cluster = df92[['customer_id', 'cluster']].groupby( 'cluster' ).count().reset_index()
df_cluster['perc_customer'] = 100*( df_cluster['customer_id'] / df_cluster['customer_id'].sum() )
# Avg Gross revenue
df_avg_gross_revenue = df92[[... | _____no_output_____ | MIT | models/pa005_insiders_deploy.ipynb | heitorfe/insiders_clustering |
10.0. Deploy to Production | df10 = df4[cols_selected].copy()
df10['cluster'] = labels
df10['recency_days'] = df10['recency_days'].astype(int)
df10['qt_products'] = df10['qt_products'].astype(int)
df10['qt_returns'] = df10['qt_returns'].astype(int)
df10['cluster'] = df10['cluster'].astype(int)
df10.dtypes | _____no_output_____ | MIT | models/pa005_insiders_deploy.ipynb | heitorfe/insiders_clustering |
stream function: $u=-\partial_y \psi$ $v=\partial_x \psi$example flow field: $\psi(x,y) = - w_{\text{max}} \frac{X}{\pi} \sin\left(\pi \frac{y}{Y}\right) \cos\left(2\pi\frac{x}{X}\right)$ | class Psi:
def __init__(self, *, X, Y, w_max):
self.X = X
self.Y = Y
self.w_max = w_max
def __call__(self, x, y):
return - self.w_max * self.X / np.pi * np.sin(np.pi * y/self.Y) * np.cos(2 * np.pi * x/self.X)
psi = Psi(X=nx*dx, Y=ny*dy, w_max=.6)
print(psi(0,0))
print(ps... | _____no_output_____ | CC-BY-4.0 | notebooks/12_arakawa_C_2D_mgrid_quiver_netCDF.ipynb | atmos-cloud-sim-uj/MoAC |
Upsert AOOS Priority Score Demo Approaching Out of Stock (AOOS)* Priority scores of work items (inventories) in AOOS work queue are calculated and upserted to InfoHub* The function `AOOS_priority_score` is defined below - for understanding the business logic, refer to the accompanying Notebook **AOOS-Priority-Score.ip... | import json
import sys
import os
import pandas as pd
import time
import numpy as np
import datetime
import copy
import json | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Import `InfoHubConnection` Class* Install `ipynb` package for the following import to work `pip install ipynb` * Make sure that the Kernel of Notebook **InfoHub.ipynb** has been run without errors | from ipynb.fs.full.InfoHub import InfoHubConnection | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Priority Score Calculation* Priority score function for _Approaching Out of Stock_ work item* The business logic is explained in detail in the accompanying Notebook **AOOS-Priority-Score.ipynb** | def AOOS_priority_score(supply_plans,
demand_plans,
starting_inventory = 0,
first_date = datetime.date(2021, 7, 31),
last_date = datetime.date(2021, 8, 31),
decay_weight = 3.0,
... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
InfoHub Connection Config* Load your InfoHub connection parameters from `credentials.json` file* `tenantId` is not required for establishing the connection, but is required in the GraphQL queries | with open("credentials.json") as config_file:
config = json.load(config_file)
url = config['url']
headers = config['headers']
tenantId = config['tenantId']
infohub = InfoHubConnection(url=url, tenantId=tenantId, headers=headers) | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Priority Score Config* `timestamp`: Timestamp is needed in `upsert` operation, in ISO format. * In production, use the current system timestamp.* `maxDate`: Active supply and demand plans till this date are used for priority score calculation * For more details, check the accompanying Notebook **AOOS-Priority-Sc... | timestamp = "2021-08-03T10:37:07+0800"
maxDate = "2021-08-31 00:00:00" | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Work Queue List* Our goal is to evaluate / re-calculate the priority score of work items in the AOOS work queue* We need the AOOS work queue object ID to get the work items that are in progress* To get the AOOS work queue object ID, we use the following query to get the list of work queues. | workqueues = infohub.get_work_queues()
for i in range(len(workqueues)):
print('WorkQueue: ', workqueues[i]['object']['name'])
print('Id: ', workqueues[i]['object']['id'])
print("--------------------------------------------------------------------------------") | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Choose `workQueueId`* Choose the workQueueId of _Inventory approaching out of stock prioritized_ | workQueueId = "516dc12d-eff6-4c51-9222-7eca88a31c5e" | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Collect Work Items* Given the work queue ID, collect all the work items | work_items = []
print("Querying work items in progress...")
work_items_list = infohub.get_workitems_in_progress(workQueueId=workQueueId)
print("\tNumber of WorkItems: {}".format(len(work_items_list)))
for i in range(len(work_items_list)):
wi = {"workItemId": work_items_list[i]['object']["id"],
"priority":... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Demo: Change in Priority Score* The priority scores are based on current supply plans and demand plans for next 30 days (`maxDate`)* In the event of a change in supply/demand plan(s), the priority score has to change to reflect the severity of going _out of stock_* We can test this by simulating a change in supply/dem... | k = 3
partNumber = work_items[k]["partNumber"]
locationIdentifier = work_items[k]["locationIdentifier"]
priority = work_items[k]["priority"]
workItemId = work_items[k]["workItemId"]
starting_inventory = work_items[k]["starting_inventory"]
print("Selected WorkItem: Object ID: {}".format(workItemId))
print("\t({}): Part-... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Step 2: Get Supply and Demand Plans* WorkItem can be identified with its unique object ID or by its unique `partNumber` and `locationIdentifier` combination* We have constructed all queries with `partNumber` and `locationIdentifier` combination for easy readability * Good practice is to use object ID as it is immun... | # Get supply plans
supply_plans = []
print("Querying supply plans ...")
plan_list = infohub.get_supplyplans(partNumber=partNumber, locationIdentifier=locationIdentifier, maxDate=maxDate)
print("\tNumber of Supply Plans: {}".format(len(plan_list)))
for i in range(len(plan_list)):
plan = {"startDate": plan_list[i]['o... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Step 3: Upsert a plan with modified quantity and/or date* Choose a supply/demand plan and change its quantity and/or date* Upsert the modified plan* You can repeat this for multiple plans (supply or demand or both) * Steps 3a and 3b | # To demonstrate the change in the priority
changed_plans = []
new_supply_plans = copy.deepcopy(supply_plans)
new_demand_plans = copy.deepcopy(demand_plans) | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
**Step 3a: _Modify Supply Plan_** | # Choose a supply plan to modify by its index
k = 0
id = supply_plans[k]["id"]
startDate = supply_plans[k]["startDate"]
quantity = supply_plans[k]["quantity"]
print("Selected Supply Plan ({}): Object ID: {}".format(k, id))
print("\tStart Date: {}; Quantity: {};".format(startDate, quantity))
new_startDate = startDate
ne... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
**Step 3b: _Modify Demand Plan_** | # Choose a demand plan to modify by its index
k = 0
id = demand_plans[k]["id"]
startDate = demand_plans[k]["startDate"]
quantity = demand_plans[k]["quantity"]
print("Selected Demand Plan ({}): Object ID: {}".format(k, id))
print("\tStart Date: {}; Quantity: {};".format(startDate, quantity))
new_startDate = startDate
ne... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Step 4: Calculate Priority Score | new_priority = AOOS_priority_score(supply_plans=new_supply_plans, demand_plans=new_demand_plans, starting_inventory=starting_inventory, inv_positive_threshold=100, inv_negative_threshold=-300)
print("Updated priority score: {}".format(new_priority))
# Results
print("Work Item / Inventory:")
print("--------------------... | _____no_output_____ | Apache-2.0 | general-solutions/external-compute/work-item-prioritization-AOOS/Upsert-AOOS-Priority-Score-Demo.ipynb | IBM/intelligence-suite-supply-chain-solutions |
Welcome to the jungle: Numpy, Scipy, Sympy, Matplotlib, PandasNumpy is a library (written is C) for numerical calculations.Scipy is written on the top of numpy, and can perfrom some more advenced task like integration, optimization, signal processingm fourier transform, etc.Sympy is for symbolic operations.Matplotlib ... | import numpy as np
np.ones((2,3))
np.eye(4)
tab2D = np.array( [[ i*2+j for j in range(2)] for i in range(3)])
tab2D | _____no_output_____ | CC-BY-3.0 | lab1_python_intro/ex2_intro_scientific_libraries.ipynb | ggruszczynski/CFDPython |
Exercice:Generate a 2D matrix 5x5 where $$ x_{i,j} = i + 100j $$Display its 3rd column.Display element at position 2,3. System of linear equationsSolve the system of equations 3 * x0 + x1 = 9 and x0 + 2 * x1 = 8See the [docs](https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html) | A = np.array([[3,1], [1,2]])
b = np.array([9,8])
x = np.linalg.solve(A, b)
x
np.allclose(np.dot(A, x), b)
# alternatively, the dot product can be expressed as
A @ x
| _____no_output_____ | CC-BY-3.0 | lab1_python_intro/ex2_intro_scientific_libraries.ipynb | ggruszczynski/CFDPython |
Model and Feature Selection Notebook Contents:- [Reading in the Data](reading5)- [Defining X and y](features5)- [AdaBoost Regressor](ada) | # imports
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import RFE
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchC... | _____no_output_____ | CC0-1.0 | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates |
Reading in the Data | # read the csv file with log scaled data
df = pd.read_csv('data/log_per_student.csv')
df.head(2)
df.columns = df.columns.str.lower() #make column names lower-case
df.set_index(df['leaid'], inplace = True) #set leaid column as index
dummies = pd.get_dummies(df['agchrt'], drop_first = True).astype('float64') # dummify ag... | _____no_output_____ | CC0-1.0 | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates |
Define X and y | # numeric X Features (excl stabbr)
X = df[[2, 3,'tfedrev', 'tstrev', 'a13', 't06', 'a11', 'u30', 'totalexp', 't40',
'v93', 'z33', 'z35', 'z36', 'z38', 'z37', 'v11', 'v13', 'v17', 'v37', 'v10', 'v12', 'v14',
'v18', 'v24', 'v38', 'w01', 'w31', 'w61', '_19h', '_21f', '_41f', '_61v']]
y = df['graduation ... | <class 'pandas.core.frame.DataFrame'>
Index: 16848 entries, 4819650 to 3407800
Data columns (total 33 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 2.0 16848 non-null float64
1 3.0 16848 non-null float64
2 tfedrev 16848 non-null float64
3 tstrev ... | CC0-1.0 | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates |
Pipe: StandardScaler / AdaBoostRegressor | pipe_ada = make_pipeline(StandardScaler(), AdaBoostRegressor())
pipe_ada.fit(X_train, y_train)
pipe_ada.score(X_train, y_train)
pipe_ada.score(X_test, y_test)
# RMSE
round(mean_squared_error(y_test, pipe_ada.predict(X_test), squared = False), 2) | _____no_output_____ | CC0-1.0 | models/notebook_5_adaboost.ipynb | vansheer/high_school_graduation_rates |
!wget --header="Host: storage.googleapis.com" --header="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36" --header="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-e... | Archive: amazon-fine-food-reviews.zip
inflating: Reviews.csv
inflating: database.sqlite
inflating: hashes.txt
| MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. | |
Amazon Fine Food Reviews AnalysisData Source: https://www.kaggle.com/snap/amazon-fine-food-reviews EDA: https://nycdatascience.com/blog/student-works/amazon-fine-foods-visualization/The Amazon Fine Food Reviews dataset consists of reviews of fine foods from Amazon.Number of reviews: 568,454Number of users: 256,059Numb... | %matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import sqlite3
import pandas as pd
import numpy as np
import nltk
import string
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVect... | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[1]. Reading Data |
# using the SQLite Table to read data.
con = sqlite3.connect('/content/database.sqlite')
#filtering only positive and negative reviews i.e.
# not taking into consideration those reviews with Score=3
# SELECT * FROM Reviews WHERE Score != 3 LIMIT 500000, will give top 500000 data points
# you can change the number to... | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
Exploratory Data Analysis [2] Data Cleaning: DeduplicationIt is observed (as shown in the table below) that the reviews data had many duplicate entries. Hence it was necessary to remove duplicates in order to get unbiased results for the analysis of the data. Following is an example: | display= pd.read_sql_query("""
SELECT *
FROM Reviews
WHERE Score != 3 AND UserId="AR5J8UI46CURR"
ORDER BY ProductID
""", con)
display.head() | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
As can be seen above the same user has multiple reviews of the with the same values for HelpfulnessNumerator, HelpfulnessDenominator, Score, Time, Summary and Text and on doing analysis it was found that ProductId=B000HDOPZG was Loacker Quadratini Vanilla Wafer Cookies, 8.82-Ounce Packages (Pack of 8) ProductId=B000H... | #Sorting data according to ProductId in ascending order
sorted_data=filtered_data.sort_values('ProductId', axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
#Deduplication of entries
final=sorted_data.drop_duplicates(subset={"UserId","ProfileName","Time","Text"}, keep='first', inplace=False)
... | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
Observation:- It was also seen that in two rows given below the value of HelpfulnessNumerator is greater than HelpfulnessDenominator which is not practically possible hence these two rows too are removed from calcualtions | display= pd.read_sql_query("""
SELECT *
FROM Reviews
WHERE Score != 3 AND Id=44737 OR Id=64422
ORDER BY ProductID
""", con)
display.head()
final=final[final.HelpfulnessNumerator<=final.HelpfulnessDenominator]
#Before starting the next phase of preprocessing lets see the number of entries left
print(final.shape)
#How ... | (4986, 10)
| MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[3]. Text Preprocessing.Now that we have finished deduplication our data requires some preprocessing before we go on further with analysis and making the prediction model.Hence in the Preprocessing phase we do the following in the order below:-1. Begin by removing the html tags2. Remove any punctuations or limited se... | # printing some random reviews
sent_0 = final['Text'].values[0]
print(sent_0)
print("="*50)
sent_1000 = final['Text'].values[1000]
print(sent_1000)
print("="*50)
sent_1500 = final['Text'].values[1500]
print(sent_1500)
print("="*50)
sent_4900 = final['Text'].values[4900]
print(sent_4900)
print("="*50)
# remove urls f... | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[3.2] Preprocess Summary | ## Similartly you can do preprocessing for review summary also. | _____no_output_____ | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4] Featurization [4.1] BAG OF WORDS | #BoW
count_vect = CountVectorizer() #in scikit-learn
count_vect.fit(preprocessed_reviews)
print("some feature names ", count_vect.get_feature_names()[:10])
print('='*50)
final_counts = count_vect.transform(preprocessed_reviews)
print("the type of count vectorizer ",type(final_counts))
print("the shape of out text BOW ... | some feature names ['aa', 'aahhhs', 'aback', 'abandon', 'abates', 'abbott', 'abby', 'abdominal', 'abiding', 'ability']
==================================================
the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shape of out text BOW vectorizer (4986, 12997)
the number of unique words 1... | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4.2] Bi-Grams and n-Grams. | #bi-gram, tri-gram and n-gram
#removing stop words like "not" should be avoided before building n-grams
# count_vect = CountVectorizer(ngram_range=(1,2))
# please do read the CountVectorizer documentation http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
# you can ch... | the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shape of out text BOW vectorizer (4986, 3144)
the number of unique words including both unigrams and bigrams 3144
| MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4.3] TF-IDF | tf_idf_vect = TfidfVectorizer(ngram_range=(1,2), min_df=10)
tf_idf_vect.fit(preprocessed_reviews)
print("some sample features(unique words in the corpus)",tf_idf_vect.get_feature_names()[0:10])
print('='*50)
final_tf_idf = tf_idf_vect.transform(preprocessed_reviews)
print("the type of count vectorizer ",type(final_tf_... | some sample features(unique words in the corpus) ['ability', 'able', 'able find', 'able get', 'absolute', 'absolutely', 'absolutely delicious', 'absolutely love', 'absolutely no', 'according']
==================================================
the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shap... | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4.4] Word2Vec | # Train your own Word2Vec model using your own text corpus
i=0
list_of_sentance=[]
for sentance in preprocessed_reviews:
list_of_sentance.append(sentance.split())
# Using Google News Word2Vectors
# in this project we are using a pretrained model by google
# its 3.3G file, once you load this into your memory
# it ... | number of words that occured minimum 5 times 3817
sample words ['product', 'available', 'course', 'total', 'pretty', 'stinky', 'right', 'nearby', 'used', 'ca', 'not', 'beat', 'great', 'received', 'shipment', 'could', 'hardly', 'wait', 'try', 'love', 'call', 'instead', 'removed', 'easily', 'daughter', 'designed', 'pri... | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4.4.1] Converting text into vectors using wAvg W2V, TFIDF-W2V [4.4.1.1] Avg W2v | # average Word2Vec
# compute average word2vec for each review.
sent_vectors = []; # the avg-w2v for each sentence/review is stored in this list
for sent in tqdm(list_of_sentance): # for each review/sentence
sent_vec = np.zeros(50) # as word vectors are of zero length 50, you might need to change this to 300 if you ... | 100%|██████████| 4986/4986 [00:06<00:00, 787.00it/s] | MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[4.4.1.2] TFIDF weighted W2v | # S = ["abc def pqr", "def def def abc", "pqr pqr def"]
model = TfidfVectorizer()
model.fit(preprocessed_reviews)
# we are converting a dictionary with word as a key, and the idf as a value
dictionary = dict(zip(model.get_feature_names(), list(model.idf_)))
# TF-IDF weighted Word2Vec
tfidf_feat = model.get_feature_name... | 100%|██████████| 4986/4986 [00:40<00:00, 123.46it/s]
| MIT | Amazon_Fine_Food_Reviews_Analysis.ipynb | charanhu/Amazon-Fine-Food-Reviews-Analysis. |
[Mongo Python Module Index](http://api.mongodb.com/python/current/py-modindex.html) | import pymongo
import bson
import datetime
from bson import ObjectId
from bson import DBRef
# mongodb
mongo_client = pymongo.MongoClient(host='mongodb://127.0.0.1:27017')
test = mongo_client.test
db = mongo_client.cloud
cas = mongo_client.cas
alarm = mongo_client.alarm
bandwidth = mongo_client.bandwidth_db
data = db... | _____no_output_____ | MIT | library_learn/pymongo.ipynb | shiyeli/jupyter_notebook |
Read processed data | (keys, components, x_train) = get_stft_data(
STEAD_PATH_DB_PROCESSED_STFT_64, 10000
) | _____no_output_____ | MIT | notebooks/notebook_gan64.ipynb | jbienkowski/saigon |
Convert streams to STFT | # STFT of the stream and then reverse STFT back into original stream
# f, t, Zxx = stft(x_1[1][0], window='hanning', fs=100, nperseg=155)
# k2 = istft(Zxx, window='hanning', fs=100, nperseg=155) | _____no_output_____ | MIT | notebooks/notebook_gan64.ipynb | jbienkowski/saigon |
Scale and reshape data | SCALING_FACTOR = int(
max(
[
abs(min([x.min() for x in x_train])),
abs(max([x.max() for x in x_train])),
]
)
)
SCALING_FACTOR
x_train /= SCALING_FACTOR
x_train = x_train.reshape(x_train.shape[0], 64, 64, 1)
train_dataset = (
tf.data.Dataset.from_tensor_slices(x_train)... | _____no_output_____ | MIT | notebooks/notebook_gan64.ipynb | jbienkowski/saigon |
Logs and Tensorboard | folder_name = f"{MODEL_NAME} at {strftime('%H:%M')}"
log_dir = os.path.join("../log/", folder_name)
try:
os.makedirs(log_dir)
except OSError as exception:
print(exception.strerror)
else:
print("Successfully created dirs!") | _____no_output_____ | MIT | notebooks/notebook_gan64.ipynb | jbienkowski/saigon |
Define GAN | def make_generator_model():
model = tf.keras.Sequential()
model.add(
layers.Dense(2 * 2 * 128, use_bias=False, input_shape=(LATENT_DIM,))
)
model.add(layers.BatchNormalization())
model.add(layers.LeakyReLU())
model.add(layers.Reshape((2, 2, 128)))
model.add(
layers.Conv2DTr... | _____no_output_____ | MIT | notebooks/notebook_gan64.ipynb | jbienkowski/saigon |
Introduction This is a basic tutorial on using Jupyter to use the scipy modules. Example of plotting sine and cosine functions in the same plot Install matplotlib through conda via: conda install -y matplotlib Below we plot a sine function from 0 to 2 pi. Pretty much what you would expect: | import math
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 3 * math.pi, 50)
y = np.sin(x)
plt.plot(x, y)
plt.show() | _____no_output_____ | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
The x values limit the range of the plot. Let's get help on the plt.plot function, so as to understand how to use it, in addition to the tutorial at http://matplotlib.org/users/pyplot_tutorial.html | help(plt.plot) | Help on function plot in module matplotlib.pyplot:
plot(*args, **kwargs)
Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following is
legal::
... | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Let's add in 'bo' string to the mix to get dots on the trace: | import math
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * math.pi, 50)
y = np.sin(x)
plt.plot(x, y, 'bo')
plt.show() | _____no_output_____ | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Let's try to add two traces, the second one is a cosine function: | import math
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2 * math.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, 'bo', x, y2, 'r+')
plt.show() | _____no_output_____ | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Example of using optimize.fmin on the sine function | import math
import numpy as np
from scipy import linalg, optimize
# Here, we called this function "func2" which is pretty arbitrary. You will need to use better name in practice, of course:
def func2(x):
return np.sin(x)
optimize.fmin(func2, math.pi - 0.01) | Optimization terminated successfully.
Current function value: -1.000000
Iterations: 17
Function evaluations: 34
| MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Pretty much what we expected. There is a minimum of -1 for this sine wave function (amplitude of 1 here ... would have been different if we multiplied the sine wave by some other factor). We can call the f function to see the value at that point which is pretty darn close to -1: | func2(4.71237414)
math.pi * 2 * 0.75 | _____no_output_____ | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Example of using optimize.root on the sine function | help(optimize.root) | Help on function root in module scipy.optimize._root:
root(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None, options=None)
Find a root of a vector function.
Parameters
----------
fun : callable
A vector function to find a root of.
x0 : ndarray
Initial guess.
... | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Let's evaludate the f function (which we know is a sine function) at not quite at the point where it is zero (at pi): | func2(math.pi * 0.75)
import math
import numpy as np
from scipy import linalg, optimize
# Here, we called this function "func2" which is pretty arbitrary. You will need to use better name in practice, of course:
def func2(x):
return np.sin(x)
optimize.root(func2, math.pi * 0.75) | _____no_output_____ | MIT | python/jupyter/basic_jupyter_scipy_tutorial.ipynb | bgoodr/how-to |
Exercise 18: Lambda Expression 1. Import the math package | import math | _____no_output_____ | MIT | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | arifmudi/The-Data-Wrangling-Workshop |
2. Define two functions, my_sine and my_cosine | def my_sine():
return lambda x: math.sin(math.radians(x))
def my_cosine():
return lambda x: math.cos(math.radians(x)) | _____no_output_____ | MIT | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | arifmudi/The-Data-Wrangling-Workshop |
3. Define sine and cosine for our purpose | sine = my_sine()
cosine = my_cosine()
math.pow(sine(30), 2) + math.pow(cosine(30), 2) | _____no_output_____ | MIT | Chapter02/.ipynb_checkpoints/Exercise 18-checkpoint.ipynb | arifmudi/The-Data-Wrangling-Workshop |
Métodos de punto fijo I En esta ocasión empezaremos a implementar un método para obtener una raiz real de una ecuación no lineal. Este método se le conoce como punto fijo, pero la variante especificamente que implementaremos ahora es la de aproximaciones sucesivas. Aproximaciones sucesivas Tenemos un polinomio $f(x) ... | from numpy import sqrt
1/(2*sqrt(12)) | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Entonces ya tenemos una formula para iterar a través:$$x_1 = g(x_0)$$es decir:$$x_1 = \sqrt{\frac{x_0 + 5}{2}}$$ | x_0 = 1
g = lambda x: sqrt((x+5)/2)
x_1 = g(x_0)
x_1 | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Y ya tenemos la primera iteración. Cuando dejaremos de iterar? Cuando el error $\varepsilon = x_1 - x_0$ sea menor a $0.001$ (para este ejemplo). | abs(x_1 - x_0) | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Como podemos ver, aun falta mucho... pero podemos decirle a la computadora que lo siga haciendo sin notsotros. Primero creamos una funcion que itere la funcion g hasta que la diferencia de las ultimas iteraciones sea menor al error. | def aprox_sucesivas(g, x0, error):
xs = [x0]
while True:
xs.append(g(xs[-1]))
if abs(xs[-1] - xs[-2]) <= error:
return xs[-1] | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Y ahora le damos a esta funcion nuestra $g(x)$, el punto donde queremos que inicie $x_0$ y el error maximo permitido. | r = aprox_sucesivas(g, 0, 0.001)
r
from numpy import sin | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Creamos una funcion en codigo, que contiene la función original, para evaluar que tan bien se aproximo la raiz. | f = lambda x: 2*x**2 - x - 5
f(r) | _____no_output_____ | MIT | Practicas/P2/Practica 2 - Metodos de punto fijo.ipynb | robblack007/clase-metodos-numericos |
Building the DatabaseWe use a database in the backend to serve the data over a REST API to our client. The database is being built with the data frame generated using the `build_game_db.ipynb` notebook. We stored it in the feather format as it is both efficient and compact. We start by reading the stored data frame. | df_tmp = pd.read_feather("spiele_db.ftr")
df_tmp | _____no_output_____ | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
We use TinyDB aus our backend. Note that TinyDB is not fit for production use. Up to a few hundred or even a few thousand entries it will do. The advantage is that it is a document database, so it should be possible to port with reasonable effort to a larger scale document database such as MongoDB or CouchDB. Note that... | if os.path.exists('spiele_tinydb.json'):
os.remove('spiele_tinydb.json')
game_db = TinyDB('spiele_tinydb.json') | _____no_output_____ | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
Now we just insert our data frame row by row. Note that this is time consuming. As a workaround we could directly manipulate the JSON but this may not work with future TinyDB versions. | for i in df_tmp.index:
game_db.insert(json.loads(df_tmp.loc[i].to_json())) | _____no_output_____ | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
Once we have the TinyDB database we can query it. The syntax is a bit clumsy, but generally it works. In my configuration case insensitive search did not work for some unknow reason. | my_query = Query()
query_result = game_db.search(my_query.game_title.matches('.*Dark.*', flags=re.IGNORECASE))
for item in query_result:
print(item["game_title"], " / ", item["game_igdb_name"], ": ", round(item["game_rating"], 2), " / ", item["game_rating_count"]) | Darksiders II Deathinitive Edition / Darksiders II: Deathinitive Edition : 74.78 / 59
Dark Cloud 2 / Dark Cloud 2 : 87.56 / 33
Darksiders III / Darksiders III : 70.46 / 80
| BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
Since we are dealing with JSON here there will be entries where some values are not set in the JSON. Unfortunately searching for them the gives an error. So we have to use a lambda function for searching. | def search_by_rating(min_rating = 0, max_rating = 100):
my_query = Query()
test_func = lambda s: True if(isinstance(s, float) and s >= min_rating and s <= max_rating) else False
return game_db.search(my_query.game_rating.test(test_func))
query_result = search_by_rating(90)
print(print(json.dumps(query_res... | [
{
"game_buy_date": " 8/4/2018",
"game_category": "Spiel ",
"game_flag": null,
"game_genres": "Shooter Indie",
"game_igdb_id": 20919,
"game_igdb_name": "In Space We Brawl",
"game_platforms": "PC (Microsoft Windows) PlayStation 3 Mac PlayStation 4 Xbox One",
... | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
The REST APITo get a list of games in our frontend on the client we want to filter by the following attributes:- Minimum Rating: Games above a certain rating as documented in the IGDB.- Maximum Rating: Games below a certain rating as documented in the IGDB. Mainly to restrict the number of results.- Minimum Rating Cou... | def search_api(min_rating = 0, max_rating = 100, min_rating_count = 0, max_playing_time = 1000):
my_query = Query()
test_rating = lambda s: True if(isinstance(s, float) and s >= min_rating and s <= max_rating) else False
test_time = lambda s: True if(isinstance(s, float) and s <= max_playing_time) else Fals... | Number of results: 23
[
{
"game_buy_date": " 25/6/2017",
"game_category": "Spiel ",
"game_flag": null,
"game_genres": "Adventure Indie",
"game_igdb_id": 9730,
"game_igdb_name": "Firewatch",
"game_platforms": "Linux PC (Microsoft Windows) Mac PlayStation 4 Xbo... | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
Summarising the result gives a better overview. We are working with lists of dictionaries a return valies of the search functions in TinyDB. | result_sorted = sorted(query_result, key=lambda x: x["game_rating"], reverse=True)
for item in result_sorted:
print(item["game_title"], " / ", item["game_igdb_name"], ": ", round(item["game_rating"], 2), " / ", item["game_rating_count"]) | INSIDE / INSIDE : 89.76 / 866
Another World / Another World : 87.06 / 114
What Remains of Edith Finch / What Remains of Edith Finch : 85.94 / 444
Super Time Force Ultra / Super Time Force Ultra : 85.25 / 23
Hotline Miami / Hotline Miami : 85.2 / 788
Sonic Mania / Sonic Mania : 84.67 / 194
... | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
Alternative DatabasesShortly tried playing around with SQL Alchemy and an SQLite database. As the base structures returned by IGDB are all JSONs substantial cleaning up would be necessary to create a proper SQL database. I stuck with TinyDB as database in the backend.Another thing to consider would be just a plain JSO... | engine = db.create_engine('sqlite://', echo=False)
df_tmp.to_sql('games', con=engine)
engine.execute("SELECT * FROM games").fetchall()
metadata = db.MetaData()
games_table = db.Table('games', metadata, autoload=True, autoload_with=engine)
print(metadata.tables)
print(games_table.columns)
print(games_table.metadata)
| immutabledict({'games': Table('games', MetaData(bind=None), Column('index', BIGINT(), table=<games>), Column('web-scraper-order', TEXT(), table=<games>), Column('game_title', TEXT(), table=<games>), Column('game_platforms', TEXT(), table=<games>), Column('game_flag', FLOAT(), table=<games>), Column('game_category', TEX... | BSD-2-Clause | TinyDB.ipynb | Nop287/game_db |
IPython: beyond plain PythonAdapted from the ICESat2 Hackweek [intro-jupyter-git](https://github.com/ICESAT-2HackWeek/intro-jupyter-git) session. Courtesy of [@fperez](https://github.com/fperez).When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to m... | print("Hi") | Hi
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Getting help: | ? | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Typing `object_name?` will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes. | import numpy as np
np.linspace?
np.isclose??
*int*? | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
An IPython quick reference card: | %quickref | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Tab completionTab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type `object_name.` to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names. | np. | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
The interactive workflow: input, output, history | 2+10
_+10 | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
You can suppress the storage and rendering of output if you append `;` to the last cell (this comes in handy when plotting with matplotlib, for example): | 10+20;
_ | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
The output is stored in `_N` and `Out[N]` variables: | _11 == Out[11] | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Previous inputs are available, too: | In[11]
_i
%history -n 1-5 | 1: print("Hi")
2: ?
3: import numpy as np
4:
import numpy as np
np.linspace?
5: np.isclose??
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
**Exercise**Use `%history?` to have a look at `%history`'s magic documentation, and write the last 10 lines of history to a file named `log.py`. Accessing the underlying operating system | !pwd
files = !ls
print("files this directory:")
print(files)
files
!echo $files
!echo {files[0].upper()} | 01-INTRO JUPYTER.IPYNB
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Note that all this is available even in multiline blocks: | import os
for i,f in enumerate(files):
if f.endswith('ipynb'):
!echo {"%02d" % i} - "{os.path.splitext(f)[0]}"
else:
print('--') | 00 - 01-Intro Jupyter
01 - 02-Beyond Plain Python
02 - 03-Rich Output
03 - 04-widgets-introduction
04 - 05-widgets-interact
05 - 06-widget_basics
--
07 - Rich Output Exercises - Custom Display Logic
08 - a-01-Git-Tutorial
09 - a-02-widgets-moreinto
--
--
--
13 - index
--
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Beyond Python: magic functionsThe IPyhton 'magic' functions are a set of commands, invoked by prepending one or two `%` signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with `--` and arguments without quotes, parenthese... | %magic | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Line vs cell magics:Magics can be applied at the single-line level or to entire cells. Line magics are identified with a single `%` prefix, while cell magics use `%%` and can only be used as the first line of the cell (since they apply to the entire cell). Some magics, like the convenient `%timeit` that ships built-in ... | %timeit list(range(1000))
%%timeit
# comment here
list(range(10))
list(range(100)) | 1.63 µs ± 175 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Line magics can be used even inside code blocks: | for i in range(1, 5):
size = i*100
print('size:', size, end=' ')
%timeit list(range(size)) | size: 100 1.09 µs ± 37.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
size: 200 1.61 µs ± 10.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
size: 300 2.78 µs ± 13.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
size: 400 4.88 µs ± 267 ns per loop (mean ± std. dev. of 7 runs... | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Magics can do anything they want with their input, so it doesn't have to be valid Python (note that the below may not work on a Windows machine, depending on how you are running Jupyter on it): | %%bash
echo "My shell is:" $SHELL
echo "My disk usage is:"
df -h | My shell is: /bin/zsh
My disk usage is:
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1s1 466Gi 439Gi 16Gi 97% 4374206 9223372036850401601 0% /
devfs 194Ki 194Ki 0Bi 100% 670 0 100% /dev
/dev/disk1s4 466Gi 10Gi ... | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Another interesting cell magic: create any file you want locally from the notebook: | %%writefile test.txt
This is a test file!
It can contain anything I want...
And more...
!cat test.txt | This is a test file!
It can contain anything I want...
And more...
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Let's see what other magics are currently defined in the system: | %lsmagic
def to_optimize(N):
total = [0,0]
ta = 0
tb = 0
for i in range(N):
for j in range(N):
a = i**2
b = j*2
total[0] += a
total[1] += b
return total
%timeit to_optimize(1_000)
%prun to_optimize(1_000) | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Running normal Python code: execution and errorsNot only can you input normal Python code, you can even paste straight from a Python or IPython shell session: | >>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b
In [1]: for i in range(10):
...: print(i, end=' ')
...: | 0 1 2 3 4 5 6 7 8 9 | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
And when your code produces errors, you can control how they are displayed with the `%xmode` magic: | %%writefile mod.py
def f(x):
return 1.0/(x-1)
def g(y):
return f(y+1) | Writing mod.py
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Now let's call the function `g` with an argument that would produce an error: | import mod
mod.g(0) | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Basic debuggingWhen running code interactively, it can be tricky to figure out how to debug... | %debug
enjoy = input('Are you enjoying this tutorial? ')
print('enjoy is:', enjoy) | Are you enjoying this tutorial? :)
| BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Running code in other languages with special `%%` magics | %%perl
@months = ("July", "August", "September");
print $months[0]; | July | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
Plotting in the notebook | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp") | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
--- A quick tour of widgetsThis is meant to provide a quick overview of some of the things you can do with Jupyter widgets. For more ideas, you can check out [the docs](https://ipywidgets.readthedocs.io/en/latest/), and the notebooks from the [ICESat2 Hackweek](https://github.com/ICESAT-2HackWeek/intro-jupyter-git) | import numpy as np
import matplotlib.pyplot as plt
import ipywidgets
%matplotlib inline
def sin_x(x, frequency=1, phase=0):
return np.sin(
2*np.pi*frequency*x + phase
)
def plot_sin_x(frequency=1, phase=0, title="a"):
x = np.linspace(-1, 1, 200)
plt.plot(x, sin_x(x, frequency, phase))
plt.t... | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
using interactive | widget = ipywidgets.interactive(plot_sin_x, frequency=1.5, phase=0.)
widget | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
specifying the widgets | mywidget = ipywidgets.interactive(
plot_sin_x,
frequency = ipywidgets.FloatSlider(min=0, max=10, value=1, display="f"),
# phase = ipywidgets.FloatSlider(min=-np.pi, max=np.pi, value=0)
phase = ipywidgets.FloatText(value=0),
title = ipywidgets.ToggleButtons(options=["a", "b"])
)
mywidget
mywidget.chi... | _____no_output_____ | BSD-3-Clause | 02-Beyond Plain Python.ipynb | yaramohajerani/intro-jupyter |
API Package: usda_com This notebook provides a simple use case for the USDA Commodity Database. The package can be downloaded via github using the following code. | import pandas as pd
data = pd.read_csv('../usda_com/data/commodities.csv')
data = data.iloc[:, 1:]
data.head()
data.to_csv('../usda_com/data/commodities.csv', index=False)
! pip install git+https://github.com/LightnerAndrew/usda_com --quiet
import os
os.chdir('..')
import usda_com
# create the query object.
qry = us... | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
API Key The first step in building and using the API is to create an account and generate an API key. https://apps.fas.usda.gov/psdonline/app/index.html/app/about1. Create an account: 2. Generate an API Key | qry.api_key = 'D892ADB8-DBC1-4AF5-BCFF-BA338AAE2B6E' | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
Explore commodity optionsThe `commodity_options` attribute holds commodity code information. | qry.commodity_options.head() | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
Although you could query the datafrmae using pandas, there is also a convenient `find_commodity_code()` method to search the Commodity names for those of interest. For this example, we will access data for fresh apples. | qry.find_commodity_code('Apples')
qry.com_selection = ['574000'] | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
Year selection The USDA records data from 1960 until the most recent data (2018 at the time of creating this notebook). The year_selection attribute takes a string in two different formats. 1. `{year0},{year1},..` will select only the years specified. 2. `{year0}:{year1}` will return all years within a given range. | qry.year_selection = '1990,2000' | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
Access Data! | raw_data = qry.run()
raw_data.head()
raw_data.columns
raw_data.MarketYear.unique() | _____no_output_____ | MIT | notebooks/Example Use Case.ipynb | LightnerAndrew/usda_com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.