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 |
|---|---|---|---|---|---|
Adding, Removing Columns, Combining `DataFrames`/`Series`It is all well and good when you already have a `DataFrame` filled with data, but it is also important to be able to add to the data that you have.We add a new column simply by assigning data to a column that does not already exist. Here we use the `.loc[:, 'COL... | securities = get_securities(symbols="AAPL", vendors='usstock')
securities
AAPL = securities.index[0]
s_1 = get_prices("usstock-free-1min", data_frequency="daily", sids=AAPL, start_date=start, end_date=end, fields='Close').loc["Close"][AAPL]
prices.loc[:, AAPL] = s_1
prices.head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
It is also just as easy to remove a column. | prices = prices.drop(AAPL, axis=1)
prices.head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Time Series Analysis with pandasUsing the built-in statistics methods for `DataFrames`, we can perform calculations on multiple time series at once! The code to perform calculations on `DataFrames` here is almost exactly the same as the methods used for `Series` above, so don't worry about re-learning everything.The `... | prices.plot()
plt.title("Collected Stock Prices")
plt.ylabel("Price")
plt.xlabel("Date"); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
The same statistical functions from our interactions with `Series` resurface here with the addition of the `axis` parameter. By specifying the `axis`, we tell pandas to calculate the desired function along either the rows (`axis=0`) or the columns (`axis=1`). We can easily calculate the mean of each columns like so: | prices.mean(axis=0) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
As well as the standard deviation: | prices.std(axis=0) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Again, the `describe()` function will provide us with summary statistics of our data if we would rather have all of our typical statistics in a convenient visual instead of calculating them individually. | prices.describe() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
We can scale and add scalars to our `DataFrame`, as you might suspect after dealing with `Series`. This again works element-wise. | (2 * prices - 50).head(5) | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Here we use the `pct_change()` method to get a `DataFrame` of the multiplicative returns of the securities that we are looking at. | mult_returns = prices.pct_change()[1:]
mult_returns.head() | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
If we use our statistics methods to standardize the returns, a common procedure when examining data, then we can get a better idea of how they all move relative to each other on the same scale. | norm_returns = (mult_returns - mult_returns.mean(axis=0))/mult_returns.std(axis=0)
norm_returns.loc['2014-01-01':'2015-01-01'].plot(); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
This makes it easier to compare the motion of the different time series contained in our example. Rolling means and standard deviations also work with `DataFrames`. | rolling_mean = prices.rolling(30).mean()
rolling_mean.columns = prices.columns
rolling_mean.plot()
plt.title("Rolling Mean of Prices")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend(); | _____no_output_____ | CC-BY-4.0 | quant_finance_lectures/Lecture04-Introduction-to-Pandas.ipynb | jonrtaylor/quant-finance-lectures |
Metacal Log JSON data| columns | Description ||---------------------|------------------------------------------------------------|| tract | || patch | ... | # Read metacal log data
df = pd.DataFrame()
#df = pd.read_json('/global/cfs/cdirs/lsst/groups/CO/heatherk/Run2.2i/metacal/metacalEval/data/metacal_logs.json', convert_dates=False)
df = pd.read_json('../data/metacal_logs.json', convert_dates=False)
# Read coadd ?,?_nImage.fits data
df_coadds = pd.DataFrame()
df_coadds.a... | (3506, 32)
| BSD-3-Clause | notebooks/metacal_stats.ipynb | heather999/metacallEval |
CPU Time vs Number of Deblended Sources | df.loc[(df['metacalmax_success']==True)&(df['ngmixmax_success']==True),"deblendedsources"].max()
# Focus on jobs where both processDeblendedCoaddsMetacalMax and processDeblendedCoaddsNGMixMax ran to completion successfully
successful_jobs = df.loc[(df['metacalmax_success'] == True)&(df['ngmixmax_success']==True)]
suc... | _____no_output_____ | BSD-3-Clause | notebooks/metacal_stats.ipynb | heather999/metacallEval |
Extended data frame | df_new['duration'] = (df_new.deadline-df_new.launched_at)/(3600*24)
df_new['duration'] = df_new['duration'].round(2)
df_new['goal_usd'] = df_new['goal'] * df_new['static_usd_rate']
df_new['goal_usd'] = df_new['goal_usd'].round(2)
#df_new['launched_at_full'] = pd.to_datetime(df_new['launched_at'], unit='s')
df_new['laun... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 209222 entries, 0 to 209221
Columns: 108 entries, backers_count to category_parent_name
dtypes: bool(5), datetime64[ns](3), float64(18), int64(16), object(66)
memory usage: 165.4+ MB
| MIT | kickstarter_02_preparation.ipynb | dominikmn/ds-kickstarter-project |
Save frame | save_dataframe(df_new, './data_frame_full_2021-03-12.pickle') | _____no_output_____ | MIT | kickstarter_02_preparation.ipynb | dominikmn/ds-kickstarter-project |
Reduced data frame | for i , val in df_new.iloc[60060,:].items():
print(i)
print(val)
print()
survival_lst = ['backers_count', 'blurb', 'country', 'created_at', 'currency', 'deadline','disable_communication', 'goal', 'launched_at','name', 'staff_pick','state',
'usd_pledged','usd_type','category_id','category_na... | _____no_output_____ | MIT | kickstarter_02_preparation.ipynb | dominikmn/ds-kickstarter-project |
Tutorial 4: A two-asset HANK modelIn this notebook we solve the two-asset HANK model from Auclert, Bardóczy, Rognlie, Straub (2021): "Using the Sequence-Space Jacobian to Solve and Estimate Heterogeneous-Agent Models" ([link to paper](https://www.bencebardoczy.com/publication/sequence-jacobian/sequence-jacobian.pdf)).... | import numpy as np
import matplotlib.pyplot as plt
from sequence_jacobian import simple, solved, combine, create_model # functions
from sequence_jacobian import grids, hetblocks # modules | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
1 Model descriptionThe household problem is characterized by the Bellman equation$$\begin{align} \tag{1}V_t(e, b_{-}, a_{-}) = \max_{c, b, a} &\left\{\frac{c^{1-\sigma}}{1-\sigma} + \beta \mathbb{E}_t V_{t+1}(e', b, a) \right\}\\c + a + b &= z_t(e) + (1 + r_t^a)a_{-} + (1 + r_t^b)b_{-} - \Psi(a, a_{-}) \\a &\geq \unde... | @solved(unknowns={'pi': (-0.1, 0.1)}, targets=['nkpc'], solver="brentq")
def pricing_solved(pi, mc, r, Y, kappap, mup):
nkpc = kappap * (mc - 1/mup) + Y(+1) / Y * (1 + pi(+1)).apply(np.log) / \
(1 + r(+1)) - (1 + pi).apply(np.log)
return nkpc | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
When our routines encounter a solved block in `blocks`, they compute its Jacobian via the the implicit function theorem, as if it was a model on its own. Given the Jacobian, the rest of the code applies without modification. 2.2 Equity price (equity & dividend)The no arbitrage condition characterizes $(p)$ conditiona... | @solved(unknowns={'p': (5, 15)}, targets=['equity'], solver="brentq")
def arbitrage_solved(div, p, r):
equity = div(+1) + p(+1) - p * (1 + r(+1))
return equity | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
2.3 Investment with adjustment costs (prod)Sometimes multiple equilibrium conditions can be combined in a self-contained solved block. Investment subject to capital adjustment costs is such a case. In particular, we can use the following four equations to solve for $(K, Q)$ conditional on $(Y, w, r)$. - Production: ... | @simple
def labor(Y, w, K, Z, alpha):
N = (Y / Z / K(-1) ** alpha) ** (1 / (1 - alpha))
mc = w * N / (1 - alpha) / Y
return N, mc
@simple
def investment(Q, K, r, N, mc, Z, delta, epsI, alpha):
inv = (K / K(-1) - 1) / (delta * epsI) + 1 - Q
val = alpha * Z(+1) * (N(+1) / K) ** (1 - alpha) * mc(+1) ... | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
3 Build DAGsOne for transition dynamics (pictured above) and one for calibrating the steady state. Step 1: Adapt HA blockWe developed an efficient backward iteration function to solve the Bellman equation in (1). Although we view this as a contribution on its own, discussing the algorithm goes beyond the scope of this... | def make_grids(bmax, amax, kmax, nB, nA, nK, nZ, rho_z, sigma_z):
b_grid = grids.agrid(amax=bmax, n=nB)
a_grid = grids.agrid(amax=amax, n=nA)
k_grid = grids.agrid(amax=kmax, n=nK)[::-1].copy()
e_grid, _, Pi = grids.markov_rouwenhorst(rho=rho_z, sigma=sigma_z, N=nZ)
return b_grid, a_grid, k_grid, e_g... | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Step 2: Complete dynamic DAG with simple blocksWe have set up all the blocks in the `sequence_jacobian/examples/two_asset.py` module. We omit the step-by-step discussion of these blocks since they should be familiar from the other model notebooks. | import sequence_jacobian.examples.two_asset as m
blocks = [hh_ext, production_solved, pricing_solved, arbitrage_solved,
m.dividend, m.taylor, m.fiscal, m.share_value,
m.finance, m.wage, m.union, m.mkt_clearing]
hank = create_model(blocks, name='Two-Asset HANK')
print(*hank.blocks, sep='\n') | <SolvedBlock 'labor_to_investment_combined_solved'>
<SolvedBlock 'pricing_solved'>
<SimpleBlock 'wage'>
<SimpleBlock 'taylor'>
<SimpleBlock 'dividend'>
<SolvedBlock 'arbitrage_solved'>
<SimpleBlock 'share_value'>
<SimpleBlock 'finance'>
<SimpleBlock 'fiscal'>
<HetBlock 'hh' with hetinput 'make_grids_marginal_cost_grid'... | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Step 3: Complete calibration DAGAnalytical:- find TFP `Z` to hit target for output `Y`- find markup `mup` to hit target for total wealth `p + Bg`- find capital share `alpha` to hit target for capital `K`- find wage `w` to hit Phillips curve given zero inflation - find disutility of labor `vphi` to hit wage Phillips cu... | blocks_ss = [hh_ext, m.partial_ss, m.union_ss,
m.dividend, m.taylor, m.fiscal, m.share_value, m.finance, m.mkt_clearing]
hank_ss = create_model(blocks_ss, name='Two-Asset HANK SS')
print(hank_ss)
print(f"Inputs: {hank_ss.inputs}")
| <Model 'Two-Asset HANK SS'>
Inputs: ['beta', 'eis', 'chi0', 'chi1', 'chi2', 'N', 'bmax', 'amax', 'kmax', 'nB', 'nA', 'nK', 'nZ', 'rho_z', 'sigma_z', 'Y', 'K', 'r', 'tot_wealth', 'Bg', 'delta', 'muw', 'frisch', 'pi', 'kappap', 'epsI', 'rstar', 'phi', 'G', 'Bh', 'omega']
| MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
4 ResultsWe cover how to pass precomputed Jacobians to the main methods. This is useful when methods that need Jacobians are used repeatedly. These are- Solve methods: `solve_impulse_linear`, `solve_impulse_nonlinear`- Jacobian methods: `jacobian`, `solve_jacobian` 4.1 Calibrate steady stateUse the calibration DAG to ... | calibration = {'Y': 1., 'N': 1.0, 'K': 10., 'r': 0.0125, 'rstar': 0.0125, 'tot_wealth': 14,
'delta': 0.02, 'pi': 0., 'kappap': 0.1, 'muw': 1.1, 'Bh': 1.04, 'Bg': 2.8,
'G': 0.2, 'eis': 0.5, 'frisch': 1., 'chi0': 0.25, 'chi2': 2, 'epsI': 4,
'omega': 0.005, 'kappaw': 0.1, 'phi'... | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Verify solution, generate `ss` from dynamic DAG. | ss = hank.steady_state(cali)
print(f"Liquid assets: {ss['B']: 0.2f}")
print(f"Asset market clearing: {ss['asset_mkt']: 0.2e}")
print(f"Goods market clearing (untargeted): {ss['goods_mkt']: 0.2e}") | Liquid assets: 1.04
Asset market clearing: 8.22e-13
Goods market clearing (untargeted): 3.29e-08
| MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
4.2 Linearized impulse responsesAs before, we can compute the general equilibrium Jacobians $G$ which is sufficient to map any shock into impulse responses. When the cost of computing a block Jacobian is non-trivial, it's a good idea to precompute it. We can supply block Jacobians for specific blocks via the `Js=` key... | exogenous = ['rstar', 'Z', 'G']
unknowns = ['r', 'w', 'Y']
targets = ['asset_mkt', 'fisher', 'wnkpc']
T = 300
J_ha = hh_ext.jacobian(ss, inputs=['N', 'r', 'ra', 'rb', 'tax', 'w'], T=T)
G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha}) | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
The time saving from re-using the Jacobian of the household block is considerable. | %time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha})
%time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T) | Wall time: 4.94 s
| MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Note that some block Jacobians may be precomputed even if others are changing. For example, we can re-use `J_ha` while evalutating the model likelihood for 100,000 draws of price and wage adjustment cost.When we're not planning to change any part of the model, it's even better to store the `H_U` directly. (To be precis... | from sequence_jacobian.classes import FactoredJacobianDict
H_U = hank.jacobian(ss, unknowns, targets, T=T, Js={'hh': J_ha})
H_U_factored = FactoredJacobianDict(H_U, T)
%time G = hank.solve_jacobian(ss, unknowns, targets, exogenous, T=T, Js={'hh': J_ha}, H_U_factored=H_U_factored) | Wall time: 343 ms
| MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Let's plot some impulse responses: | rhos = np.array([0.2, 0.4, 0.6, 0.8])
drstar = -0.0025 * rhos ** (np.arange(T)[:, np.newaxis])
dY = 100 * G['Y']['rstar'] @ drstar
plt.plot(dY[:21])
plt.title(r'Output response to 25 bp monetary policy shocks with $\rho=(0.2 ... 0.8)$')
plt.xlabel('quarters')
plt.ylabel('% deviation from ss')
plt.show() | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
4.3 Nonlinear impulse responsesLet's compute the nonlinear impulse response for the $\rho=0.6$ shock above.- Don't forget to use the saved Jacobian.- Note how to look up and change options specific to (block type, method) pairs. | hank['pricing_solved'].solve_impulse_nonlinear_options | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
By default, `SolvedBlock.solve_impulse_linear` prints the error in each iteration (`verbose=True`). Let's turn this off for the internal solved blocks. | td_nonlin = hank.solve_impulse_nonlinear(ss, unknowns, targets, {"rstar": drstar[:, 2]},
Js={'hh': J_ha}, H_U_factored=H_U_factored,
options={'pricing_solved': {'verbose': False},
'arbitra... | Solving Two-Asset HANK for ['r', 'w', 'Y'] to hit ['asset_mkt', 'fisher', 'wnkpc']
On iteration 0
max error for asset_mkt is 3.92E-06
max error for fisher is 2.50E-03
max error for wnkpc is 4.72E-08
On iteration 1
max error for asset_mkt is 2.66E-04
max error for fisher is 1.55E-06
max error for wnkpc... | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
We see rapid convergence and mild nonlinearities in the solution. | dY_nonlin = 100 * td_nonlin['Y']
plt.plot(dY[:21, 2], label='linear', linestyle='-', linewidth=2.5)
plt.plot(dY_nonlin[:21], label='nonlinear', linestyle='--', linewidth=2.5)
plt.title(r'Consumption response to 1% monetary policy shock')
plt.xlabel('quarters')
plt.ylabel('% deviation from ss')
plt.legend()
plt.show() | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
Alternatively, we can compute the impulse response to a version of the shock scaled down to 10% of its original size. | td_nonlin = hank.solve_impulse_nonlinear(ss, unknowns, targets, {"rstar": 0.1 * drstar[:, 2]},
Js={'hh': J_ha},
options={'pricing_solved': {'verbose': False},
'arbitrage_solved': {'verbose... | _____no_output_____ | MIT | notebooks/two_asset.ipynb | gboehl/sequence-jacobian |
損失関数とトレーニング誤差・テスト誤差 | par = np.linspace(-3,3,50) # パラメータの範囲
te_err = (1+par**2)/2 # テスト誤差
# テスト誤差をプロット
for i in range(10):
z = np.random.normal(size=20) # データ生成
trerr = np.mean(np.subtract.outer(z,par)**2/2, axis=0) # トレーニング誤差
plt.plot(par,trerr,'b--',linewidth=2) # トレーニング誤差をプロット
plt.... | _____no_output_____ | MIT | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python |
テスト誤差の推定:交差検証法 | from sklearn.tree import DecisionTreeRegressor
n, K = 100, 10 # 設定:データ数100, 10重CV.
# データ生成
x = np.random.uniform(-2,2,n) # 区間[-2,2]上の一様分布
y = np.sin(2*np.pi*x)/x + np.random.normal(scale=0.5,size=n)
# データをグループ分け
cv_idx = np.tile(np.arange(K), int(np.ceil(n/K)))[:n]
maxdepths = np... | _____no_output_____ | MIT | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python |
ROC曲線とAUC | n = 100 # データ数 100
xp = np.random.normal(loc=1,size=n*2).reshape(n,2) # 信号アリ
xn = np.random.normal(size=n*2).reshape(n,2) # 信号ナシ
# F1 のAUC
np.mean(np.subtract.outer(xp[:,0],xn[:,0]) >= 0)
# F2 のAUC
np.mean(np.subtract.outer(np.sum(xp,1),np.sum(xn,1)) >= 0)
n = 10000 # データ数 10000
xp = np.random.normal(lo... | _____no_output_____ | MIT | ch04eval.ipynb | kanamori-takafumi/book_StatMachineLearn_with_Python |
Automatic correspondences matching. GoalIn this chapter,We will mix up the feature matching and findHomography from calib3d module to find known objects in a complex image.BasicsSo what we did in last session? We used a queryImage, found some feature points in it, we took another trainImage, found the features in that ... | import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img1 = cv.imread('hg_2_2.jpg',0) # queryImage
img2 = cv.imread('hg_2_8.jpg',0) # trainImage
# Initiate SIFT detector
sift = cv.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1... | 3283
| MIT | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace |
Now we set a condition that atleast 10 matches (defined by MIN_MATCH_COUNT) are to be there to find the object. Otherwise simply show a message saying not enough matches are present.If enough matches are found, we extract the locations of matched keypoints in both the images. They are passed to find the perspective tra... | src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
print(len(src_pts))
M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)
matchesMask = mask.ravel().tolist()
print(M)
h,w = ... | 3283
[[ 6.53453067e-01 2.06501669e-01 -5.51251650e+00]
[-2.02967609e-01 6.57965961e-01 9.85007522e+02]
[ 1.24191783e-06 -2.13203451e-07 1.00000000e+00]]
| MIT | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace |
Finally we draw our inliers (if successfully found the object) or matching keypoints (if failed). | draw_params = dict(matchColor = (0,255,0), # draw matches in green color
singlePointColor = None,
matchesMask = matchesMask, # draw only inliers
flags = 2)
img3 = cv.drawMatches(img1,kp1,img2,kp2,good,(0,255,0),**draw_params)
plt.imshow(img3, 'gray'),plt.show()
#... | _____no_output_____ | MIT | CW1/OpenCV_Implementation/T2.hg.ipynb | lampard2a4/ICL-CVPR-Workspace |
ColorAIBy: Mark John A. VelmonteColorAi is a type of simple supervised classification machine learning AI. It can classify what shade of color the given rgb is and can also learn new color base on what the teacher teach it. The performance of this AI will depend on what you teach it. It uses KNN (K-nearest neighbor) an... | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
from datetime import datetime
from sklearn import metrics
from sklearn.model_selection import train_test_split
import matplotlib.image as mpimg
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestCla... | _____no_output_____ | MIT | Color_Ai/Learner_Color_Ai/Color AI.ipynb | xxmeowxx/AI-s |
A.2.5 The LBM Code (D2Q9) | # LBM advection-diffusion D2Q9
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
n = 100
m = 100
f = np.zeros((9,n+1,m+1), dtype=float)
feq = np.zeros(9,dtype=float)
rho = np.zeros((n+1,m+1), dtype=float)
x = np.zeros(n+1, dtype=float)
y = np.zeros(m+1,dtype=float)
w = np.zeros(9,dtype=float)
u ... | _____no_output_____ | MIT | Chapter4-3.ipynb | huiselilun/LBM_Applications |
Music Recommendation using AutoML Tables OverviewIn this notebook we will see how [AutoML Tables](https://cloud.google.com/automl-tables/) can be used to make music recommendations to users. AutoML Tables is a supervised learning service for structured data that can vastly simplify the model building process. DatasetA... | ! pip install --upgrade --quiet google-cloud-automl google-cloud-bigquery | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Restart the kernel to allow `automl_v1beta1` to be imported. The following cell should succeed after a kernel restart: | from google.cloud import automl_v1beta1 | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
1.2 Import libraries and define constants Populate the following cell with the necessary constants and run it to initialize constants and create clients for BigQuery and AutoML Tables. | # The GCP project id.
PROJECT_ID = ""
# The region to use for compute resources (AutoML isn't supported in some regions).
LOCATION = "us-central1"
# A name for the AutoML tables Dataset to create.
DATASET_DISPLAY_NAME = ""
# The BigQuery dataset to import data from (doesn't need to exist).
INPUT_BQ_DATASET = ""
# The B... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Import relevant packages and initialize clients for BigQuery and AutoML Tables. | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from google.cloud import automl_v1beta1
from google.cloud import bigquery
from google.cloud import exceptions
import seaborn as sns
%matplotlib inline
tables_client = automl_v1beta1.TablesClient(project=PROJ... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
2. Create a Dataset In order to train a model, a structured dataset must be injested into AutoML tables from either BigQuery or Google Cloud Storage. Once injested, the user will be able to cherry pick columns to use as features, labels, or weights and configure the loss function. 2.1 Create BigQuery table First, do ... | query = """
WITH
songs AS (
SELECT CONCAT(track_name, " by ", artist_name) AS song,
MAX(tags) as tags
FROM `listenbrainz.listenbrainz.listen`
GROUP BY song
HAVING tags != ""
ORDER BY COUNT(*) DESC
LIMIT 10000
),
user_songs AS (
SELECT user_name AS user, A... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
2.2 Create AutoML Dataset Create a Dataset by importing the BigQuery table that was just created. Importing data may take a few minutes or hours depending on the size of your data. | dataset = tables_client.create_dataset(
dataset_display_name=DATASET_DISPLAY_NAME)
dataset_bq_input_uri = 'bq://{0}.{1}.{2}'.format(
PROJECT_ID, INPUT_BQ_DATASET, INPUT_BQ_TABLE)
import_data_response = tables_client.import_data(
dataset=dataset, bigquery_input_uri=dataset_bq_input_uri)
import_data_result =... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Inspect the datatypes assigned to each column. In this case, the `song` and `artist` should be categorical, not textual. | list_column_specs_response = tables_client.list_column_specs(
dataset_display_name=DATASET_DISPLAY_NAME)
column_specs = {s.display_name: s for s in list_column_specs_response}
def print_column_specs(column_specs):
"""Parses the given specs and prints each column and column type."""
data_types = automl_v1be... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
2.3 Update Dataset params Sometimes, the types AutoML Tables automatically assigns each column will be off from that they were intended to be. When that happens, we need to update Tables with different types for certain columns.In this case, set the `song` and `artist` column types to `CATEGORY`. | for col in ["song", "artist"]:
tables_client.update_column_spec(dataset_display_name=DATASET_DISPLAY_NAME,
column_spec_display_name=col,
type_code="CATEGORY")
list_column_specs_response = tables_client.list_column_specs(
dataset_display_... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Not all columns are feature columns, in order to train a model, we need to tell Tables which column should be used as the target variable and, optionally, which column should be used as sample weights. | tables_client.set_target_column(dataset_display_name=DATASET_DISPLAY_NAME,
column_spec_display_name="label")
tables_client.set_weight_column(dataset_display_name=DATASET_DISPLAY_NAME,
column_spec_display_name="weight") | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
3. Create a Model Once the Dataset has been configured correctly, we can tell AutoML Tables to train a new model. The amount of resources spent to train this model can be adjusted using a parameter called `train_budget_milli_node_hours`. As the name implies, this puts a maximum budget on how many resources a training ... | tables_client.create_model(
model_display_name=MODEL_DISPLAY_NAME,
dataset_display_name=DATASET_DISPLAY_NAME,
train_budget_milli_node_hours= MODEL_TRAIN_HOURS * 1000).result() | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
4. Model Evaluation Because we are optimizing a surrogate problem (predicting the similarity between `(user, song)` pairs) in order to achieve our final objective of producing a list of recommended songs for a user, it's difficult to tell how well the model performs by looking only at the final loss function. Instead,... | users = ["rob", "fiveofoh", "Aerion"]
training_table = "{}.{}.{}".format(PROJECT_ID, INPUT_BQ_DATASET, INPUT_BQ_TABLE)
query = """
WITH user as (
SELECT user,
user_tags0, user_tags1, user_tags2, user_tags3, user_tags4,
user_tags5, user_tags6, user_tags7, user_tags8, user_tags9,
user_t... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
4.2 Make predictions Once the prediction table is created, start a batch prediction job. This may take a few minutes. | preds_bq_input_uri = "bq://{}.{}.{}".format(PROJECT_ID, INPUT_BQ_DATASET, eval_table)
preds_bq_output_uri = "bq://{}".format(PROJECT_ID)
response = tables_client.batch_predict(model_display_name=MODEL_DISPLAY_NAME,
bigquery_input_uri=preds_bq_input_uri,
... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
With the similarity predictions for `rob`, we can order by the predictions to get a ranked list of songs to recommend to `rob`. | n = 10
query = """
SELECT user, song, tables.score as score, a.label as pred_label,
b.label as true_label
FROM `{}.predictions` a, UNNEST(predicted_label)
LEFT JOIN `{}` b USING(user, song)
WHERE user = "{}" AND CAST(tables.value AS INT64) = 1
ORDER BY score DESC
LIMIT {}
""".format(output... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
4.3 Evaluate predictions Precision@k and Recall@kTo evaluate the recommendations, we can look at the precision@k and recall@k of our predictions for `rob`. Run the cells below to load the recommendations into a pandas dataframe and plot the precisions and recalls at various top-k recommendations. | query = """
WITH
top_k AS (
SELECT user, song, label,
ROW_NUMBER() OVER (PARTITION BY user ORDER BY label + weight DESC) as user_rank
FROM `{0}`
)
SELECT user, song, tables.score as score, b.label,
ROW_NUMBER() OVER (ORDER BY tables.score DESC) as rank, user_rank
... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Achieving a high precision@k means a large proportion of top-k recommended items are relevant to the user. Recall@k shows what proportion of all relevant items appeared in the top-k recommendations. Mean Average Precision (MAP)Precision@k is a good metric for understanding how many relevant recommendations we might ma... | def calculate_ap(precision):
ap = [precision[0]]
for p in precision[1:]:
ap.append(ap[-1] + p)
ap = [x / (n + 1) for x, n in zip(ap, range(len(ap)))]
return ap
ap_at_k = {user: calculate_ap(pk)
for user, pk in precision_at_k.items()}
num_k = 500
map_at_k = [sum([ap_at_k[user][k] for... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
5. Cleanup The following cells clean up the BigQuery tables and AutoML Table Datasets that were created with this notebook to avoid additional charges for storage. 5.1 Delete the Model and Dataset | tables_client.delete_model(model_display_name=MODEL_DISPLAY_NAME)
tables_client.delete_dataset(dataset_display_name=DATASET_DISPLAY_NAME) | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
5.2 Delete BigQuery datasets In order to delete BigQuery tables, make sure the service account linked to this notebook has a role with the `bigquery.tables.delete` permission such as `Big Query Data Owner`. The following command displays the current service account.IAM permissions can be adjusted [here](https://consol... | !gcloud config list account --format "value(core.account)" | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Clean up the BigQuery tables created by this notebook. | # Delete the prediction dataset.
dataset_id = str(output_uri[5:].replace(":", "."))
bq_client.delete_dataset(dataset_id, delete_contents=True, not_found_ok=True)
# Delete the training dataset.
dataset_id = "{0}.{1}".format(PROJECT_ID, INPUT_BQ_DATASET)
bq_client.delete_dataset(dataset_id, delete_contents=True, not_fou... | _____no_output_____ | Apache-2.0 | tables/automl/notebooks/music_recommendation/music_recommendation.ipynb | CodingFanSteve/python-docs-samples |
Data School's top 25 pandas tricks ([video](https://www.youtube.com/watch?v=RlIiVeig3hc))- Watch the [complete pandas video series](https://www.dataschool.io/easier-data-analysis-with-pandas/)- Connect on [Twitter](https://twitter.com/justmarkham), [Facebook](https://www.facebook.com/DataScienceSchool/), and [LinkedIn... | import pandas as pd
import numpy as np
drinks = pd.read_csv('http://bit.ly/drinksbycountry')
movies = pd.read_csv('http://bit.ly/imdbratings')
orders = pd.read_csv('http://bit.ly/chiporders', sep='\t')
orders['item_price'] = orders.item_price.str.replace('$', '').astype('float')
stocks = pd.read_csv('http://bit.ly/smal... | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
1. Show installed versions Sometimes you need to know the pandas version you're using, especially when reading the pandas documentation. You can show the pandas version by typing: | pd.__version__ | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
But if you also need to know the versions of pandas' dependencies, you can use the `show_versions()` function: | pd.show_versions() |
INSTALLED VERSIONS
------------------
commit: None
python: 3.7.1.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None
pandas: 0.23.4
pytest: 4.0.2
pip: 18.1
setuptools: 40.6.3
Cython:... | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You can see the versions of Python, pandas, NumPy, matplotlib, and more. 2. Create an example DataFrame Let's say that you want to demonstrate some pandas code. You need an example DataFrame to work with.There are many ways to do this, but my favorite way is to pass a dictionary to the DataFrame constructor, in which ... | df = pd.DataFrame({'col one':[100, 200], 'col two':[300, 400]})
df | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Now if you need a much larger DataFrame, the above method will require way too much typing. In that case, you can use NumPy's `random.rand()` function, tell it the number of rows and columns, and pass that to the DataFrame constructor: | pd.DataFrame(np.random.rand(4, 8)) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
That's pretty good, but if you also want non-numeric column names, you can coerce a string of letters to a list and then pass that list to the columns parameter: | pd.DataFrame(np.random.rand(4, 8), columns=list('abcdefgh')) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
As you might guess, your string will need to have the same number of characters as there are columns. 3. Rename columns Let's take a look at the example DataFrame we created in the last trick: | df | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
I prefer to use dot notation to select pandas columns, but that won't work since the column names have spaces. Let's fix this.The most flexible method for renaming columns is the `rename()` method. You pass it a dictionary in which the keys are the old names and the values are the new names, and you also specify the ax... | df = df.rename({'col one':'col_one', 'col two':'col_two'}, axis='columns') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
The best thing about this method is that you can use it to rename any number of columns, whether it be just one column or all columns.Now if you're going to rename all of the columns at once, a simpler method is just to overwrite the columns attribute of the DataFrame: | df.columns = ['col_one', 'col_two'] | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Now if the only thing you're doing is replacing spaces with underscores, an even better method is to use the `str.replace()` method, since you don't have to type out all of the column names: | df.columns = df.columns.str.replace(' ', '_') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
All three of these methods have the same result, which is to rename the columns so that they don't have any spaces: | df | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Finally, if you just need to add a prefix or suffix to all of your column names, you can use the `add_prefix()` method... | df.add_prefix('X_') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
...or the `add_suffix()` method: | df.add_suffix('_Y') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
4. Reverse row order Let's take a look at the drinks DataFrame: | drinks.head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
This is a dataset of average alcohol consumption by country. What if you wanted to reverse the order of the rows?The most straightforward method is to use the `loc` accessor and pass it `::-1`, which is the same slicing notation used to reverse a Python list: | drinks.loc[::-1].head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
What if you also wanted to reset the index so that it starts at zero?You would use the `reset_index()` method and tell it to drop the old index entirely: | drinks.loc[::-1].reset_index(drop=True).head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
As you can see, the rows are in reverse order but the index has been reset to the default integer index. 5. Reverse column order Similar to the previous trick, you can also use `loc` to reverse the left-to-right order of your columns: | drinks.loc[:, ::-1].head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
The colon before the comma means "select all rows", and the `::-1` after the comma means "reverse the columns", which is why "country" is now on the right side. 6. Select columns by data type Here are the data types of the drinks DataFrame: | drinks.dtypes | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Let's say you need to select only the numeric columns. You can use the `select_dtypes()` method: | drinks.select_dtypes(include='number').head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
This includes both int and float columns.You could also use this method to select just the object columns: | drinks.select_dtypes(include='object').head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You can tell it to include multiple data types by passing a list: | drinks.select_dtypes(include=['number', 'object', 'category', 'datetime']).head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You can also tell it to exclude certain data types: | drinks.select_dtypes(exclude='number').head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
7. Convert strings to numbers Let's create another example DataFrame: | df = pd.DataFrame({'col_one':['1.1', '2.2', '3.3'],
'col_two':['4.4', '5.5', '6.6'],
'col_three':['7.7', '8.8', '-']})
df | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
These numbers are actually stored as strings, which results in object columns: | df.dtypes | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
In order to do mathematical operations on these columns, we need to convert the data types to numeric. You can use the `astype()` method on the first two columns: | df.astype({'col_one':'float', 'col_two':'float'}).dtypes | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
However, this would have resulted in an error if you tried to use it on the third column, because that column contains a dash to represent zero and pandas doesn't understand how to handle it.Instead, you can use the `to_numeric()` function on the third column and tell it to convert any invalid input into `NaN` values: | pd.to_numeric(df.col_three, errors='coerce') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
If you know that the `NaN` values actually represent zeros, you can fill them with zeros using the `fillna()` method: | pd.to_numeric(df.col_three, errors='coerce').fillna(0) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Finally, you can apply this function to the entire DataFrame all at once by using the `apply()` method: | df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
df | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
This one line of code accomplishes our goal, because all of the data types have now been converted to float: | df.dtypes | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
8. Reduce DataFrame size pandas DataFrames are designed to fit into memory, and so sometimes you need to reduce the DataFrame size in order to work with it on your system.Here's the size of the drinks DataFrame: | drinks.info(memory_usage='deep') | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 193 entries, 0 to 192
Data columns (total 6 columns):
country 193 non-null object
beer_servings 193 non-null int64
spirit_servings 193 non-null int64
wine_servings 193 non-null int64
total_litre... | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You can see that it currently uses 30.4 KB.If you're having performance problems with your DataFrame, or you can't even read it into memory, there are two easy steps you can take during the file reading process to reduce the DataFrame size.The first step is to only read in the columns that you actually need, which we s... | cols = ['beer_servings', 'continent']
small_drinks = pd.read_csv('http://bit.ly/drinksbycountry', usecols=cols)
small_drinks.info(memory_usage='deep') | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 193 entries, 0 to 192
Data columns (total 2 columns):
beer_servings 193 non-null int64
continent 193 non-null object
dtypes: int64(1), object(1)
memory usage: 13.6 KB
| MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
By only reading in these two columns, we've reduced the DataFrame size to 13.6 KB.The second step is to convert any object columns containing categorical data to the category data type, which we specify with the "dtype" parameter: | dtypes = {'continent':'category'}
smaller_drinks = pd.read_csv('http://bit.ly/drinksbycountry', usecols=cols, dtype=dtypes)
smaller_drinks.info(memory_usage='deep') | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 193 entries, 0 to 192
Data columns (total 2 columns):
beer_servings 193 non-null int64
continent 193 non-null category
dtypes: category(1), int64(1)
memory usage: 2.3 KB
| MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
By reading in the continent column as the category data type, we've further reduced the DataFrame size to 2.3 KB.Keep in mind that the category data type will only reduce memory usage if you have a small number of categories relative to the number of rows. 9. Build a DataFrame from multiple files (row-wise) Let's say ... | pd.read_csv('data/stocks1.csv') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Here's the second day: | pd.read_csv('data/stocks2.csv') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
And here's the third day: | pd.read_csv('data/stocks3.csv') | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You could read each CSV file into its own DataFrame, combine them together, and then delete the original DataFrames, but that would be memory inefficient and require a lot of code.A better solution is to use the built-in glob module: | from glob import glob | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
You can pass a pattern to `glob()`, including wildcard characters, and it will return a list of all files that match that pattern.In this case, glob is looking in the "data" subdirectory for all CSV files that start with the word "stocks": | stock_files = sorted(glob('data/stocks*.csv'))
stock_files | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
glob returns filenames in an arbitrary order, which is why we sorted the list using Python's built-in `sorted()` function.We can then use a generator expression to read each of the files using `read_csv()` and pass the results to the `concat()` function, which will concatenate the rows into a single DataFrame: | pd.concat((pd.read_csv(file) for file in stock_files)) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Unfortunately, there are now duplicate values in the index. To avoid that, we can tell the `concat()` function to ignore the index and instead use the default integer index: | pd.concat((pd.read_csv(file) for file in stock_files), ignore_index=True) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
10. Build a DataFrame from multiple files (column-wise) The previous trick is useful when each file contains rows from your dataset. But what if each file instead contains columns from your dataset?Here's an example in which the drinks dataset has been split into two CSV files, and each file contains three columns: | pd.read_csv('data/drinks1.csv').head()
pd.read_csv('data/drinks2.csv').head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Similar to the previous trick, we'll start by using `glob()`: | drink_files = sorted(glob('data/drinks*.csv')) | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
And this time, we'll tell the `concat()` function to concatenate along the columns axis: | pd.concat((pd.read_csv(file) for file in drink_files), axis='columns').head() | _____no_output_____ | MIT | Pandas/.ipynb_checkpoints/top_25_pandas_tricks-checkpoint.ipynb | piszewc/python-deep-learning-data-science |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.