<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged pandas</title>
<link>https://coderlegion.com/tag/pandas</link>
<description>Powered by Question2Answer</description>
<item>
<title>Building Decision Trees with Pandas and Scikit-learn</title>
<link>https://coderlegion.com/24636/building-decision-trees-with-pandas-and-scikit-learn</link>
<description>&lt;h4 id=&quot;the-theory&quot;&gt;The Theory&lt;/h4&gt;
&lt;p&gt;So what's a Decision Tree Regressor and how does it work?&lt;br&gt;
It's a regression model so it returns continuous numerical values. It gets a prediction by asking a series of yes/no questions about the chosen features, building a binary tree structure where each question splits the data further until it reaches a prediction at the leaf node.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;It learns by choosing which questions to ask&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;So for a given feature, a &quot;split&quot; is a threshold value that divides the data into two groups, those above and those below.&lt;/p&gt;
&lt;p&gt;So say we wanted to make predictions on house price and we have features like the number of rooms, the size of the land, etc. Then at each node the algorithm tries &lt;strong&gt;every possible split across every feature&lt;/strong&gt; and picks the one that minimises the &lt;strong&gt;mean squared error (MSE)&lt;/strong&gt; of the resulting groups i.e. the split that produces two groups &lt;strong&gt;where house prices&lt;/strong&gt; within each group are as similar to each other as possible &lt;em&gt;( it sums the MSE from each set of two groups and picks the set with the lowest combined MSE).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Where,&lt;/p&gt;
&lt;p&gt;\[\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (x_i - \bar{x})^2\]&lt;/p&gt;
&lt;p&gt;&lt;em&gt;example:&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;| &lt;code&gt;Split 1: Rooms &amp;lt; 2&lt;/code&gt; | &lt;code&gt;Group A [1]&lt;/code&gt; |              &lt;code&gt;         Group B [2, 3, 4, 5]&lt;/code&gt; |&lt;br&gt;
| &lt;code&gt;Split 2: Rooms &amp;lt; 3&lt;/code&gt; | &lt;code&gt;Group A [1, 2]&lt;/code&gt; | &lt;code&gt;Group B [3, 4, 5]&lt;/code&gt; |&lt;br&gt;
| &lt;code&gt;Split 3: Rooms &amp;lt; 4&lt;/code&gt; | &lt;code&gt;Group A [1, 2, 3]&lt;/code&gt; | &lt;code&gt;Group B [4, 5]&lt;/code&gt; |&lt;br&gt;
| &lt;code&gt;Split 4: Rooms &amp;lt; 5&lt;/code&gt; | &lt;code&gt;Group A [1, 2, 3,4]&lt;/code&gt; | &lt;code&gt;Group B [5]&lt;/code&gt; |&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What value does the leaf node actually hold?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This is the key bit. During training, multiple houses end up at each leaf node. The predicted value stored at that leaf is simply the &lt;strong&gt;mean house price of all training houses that landed there&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How do we know if our model is any good?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A reasonable way to validate the model is to compare, on average, how close a prediction is to the actual value. We will use Mean Absolute Error (MAE).&lt;/p&gt;
&lt;p&gt;\[MAE = \frac{1}{n} \sum_{i=1}^{n} |y_i - \hat{y}_i|\]&lt;/p&gt;
&lt;p&gt;At this point you may be wondering why are we using MSE for training and MAE for validation. Can't we just pick one metric and use it for splitting the tree and validating it?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;We use MSE for training because it's faster than MAE&lt;/strong&gt;. During training, the tree has to calculate errors for millions of potential splits. Because MSE uses squared numbers, it unlocks a clever mathematical shortcut (variance reduction) that lets the computer calculate splits using a simple running tally.&lt;/p&gt;
&lt;p&gt;\[\sum (y_i - \bar{y})^2 = \sum y_i^2 - \frac{(\sum y_i)^2}{n}\]&lt;/p&gt;
&lt;p&gt;Look closely at the right side of the identity. There are no subtractions between individual data points and the mean. Instead, the entire formula is built out of only three components, The sum of all squared target values, the sum of all target values &lt;em&gt;(which is then squared)&lt;/em&gt; and the count n.&lt;/p&gt;
&lt;p&gt;The computer can keep a running tally of the &lt;strong&gt;sums&lt;/strong&gt;, the &lt;strong&gt;squared sums&lt;/strong&gt;, and the &lt;strong&gt;counts&lt;/strong&gt; as it slides through split points. It never has to look back at individual data points to calculate the error for a group.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;We validate with MAE because humans understand it&lt;/strong&gt;: MSE leaves you with an error in &quot;squared units&quot; &lt;em&gt;(like squared euros)&lt;/em&gt;, which would probably raise a few eyebrows at your local bank.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Limitations to consider.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Decision Tree tends to &lt;strong&gt;overfit&lt;/strong&gt; because it memorises the training data rather than learning general patterns. This may result in highly specific &quot;rules&quot; that only apply to historical data, causing it to struggle to generalise.&lt;/p&gt;
&lt;p&gt;When you train a decision tree, it uses a &lt;strong&gt;greedy algorithm&lt;/strong&gt;. This means at every single split, it only cares about making the absolute perfect decision for the data right in front of it &lt;em&gt;at that exact moment&lt;/em&gt;. It doesn't look ahead, and it doesn't plan for the future.&lt;/p&gt;
&lt;p&gt;If you don't stop it (by setting limits like &lt;code&gt;max_depth&lt;/code&gt;), the tree will keep asking questions until it has separated every single unique case in your training set into its own tiny leaf node.&lt;/p&gt;
&lt;p&gt;This is exactly why &lt;strong&gt;Ensemble Methods&lt;/strong&gt; like XGBoost exist - it builds hundreds of shallow trees and combines them, which is far more robust. Think of a Decision Tree as the foundation concept that XGBoost is built on top of.&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;the-code&quot;&gt;The Code&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;Learning path:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Explore the data and identify prediction target&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Transform - Clean the data&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select features and Model type&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Train the model - find patterns from the data&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Predict and Evaluate the model&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimise the model&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;step-1-load-and-explore-the-data&quot;&gt;&lt;strong&gt;Step 1&lt;/strong&gt;: Load and Explore the data&lt;/h4&gt;
&lt;p&gt;Using Pandas to read from a csv file and return a pandas DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd

housing_df = pd.read_csv('./datasets/housing_data.csv')

print(f&quot;Statistical Summary \n {housing_df.describe()}&quot;)

print(f&quot;Dataset Features \n {housing_df.columns}&quot;) 
&lt;/code&gt;&lt;/pre&gt;
&lt;details data-node-type=&quot;hn-details-summary&quot;&gt;
&lt;summary&gt;Output&lt;/summary&gt;
&lt;p&gt;&lt;code&gt;Statistical Summary&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Rooms Price ... Longtitude&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Propertycount&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;count 13580.000000 1.358000e+04 ... 13580.000000 13580.000000&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;mean 2.937997 1.075684e+06 ... 144.995216 7454.417378&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;std 0.955748 6.393107e+05 ... 0.103916 4378.581772&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;min 1.000000 8.500000e+04 ... 144.431810 249.000000&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;25% 2.000000 6.500000e+05 ... 144.929600 4380.000000&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;50% 3.000000 9.030000e+05 ... 145.000100 6555.000000&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;75% 3.000000 1.330000e+06 ... 145.058305 10331.000000&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;max 10.000000 9.000000e+06 ... 145.526350 21650.000000&lt;/code&gt;&lt;/p&gt;
&lt;/details&gt;&lt;details data-node-type=&quot;hn-details-summary&quot;&gt;
&lt;summary&gt;Output&lt;/summary&gt;
&lt;p&gt;&lt;code&gt;Dataset Features&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Index(['Suburb', 'Address', 'Rooms', 'Type', 'Price', 'Method', 'SellerG', 'Date', 'Distance', 'Postcode', 'Bedroom2', 'Bathroom', 'Car', 'Landsize', 'BuildingArea', 'YearBuilt', 'CouncilArea', 'Lattitude', 'Longtitude', 'Regionname', 'Propertycount'], dtype='object')&lt;/code&gt;&lt;/p&gt;
&lt;/details&gt;
&lt;h4 id=&quot;step-2-transform-the-data&quot;&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Transform the data&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;(i)&lt;/strong&gt; Remove any rows that have NaN &lt;em&gt;(missing) value ( axis: 0 -&amp;gt; rows, 1 -&amp;gt; columns )&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;clean_housing_df = housing_df.dropna(axis=0)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;(ii)&lt;/strong&gt; Select the &lt;em&gt;prediction target&lt;/em&gt; 'y' and the &lt;em&gt;features 'X'&lt;/em&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;y = clean_housing_df.Price
features = ['Rooms', 'Bathroom', 'Landsize', 'Longtitude', 'Lattitude']
X = clean_housing_df[features]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;(iii)&lt;/strong&gt; Split the data into a training set and validation set&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from sklearn.model_selection import train_test_split

train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;step-3-select-model-type-and-train-&quot;&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Select Model type and train.&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;(i)&lt;/strong&gt; Scikit-learn Decision Tree Regressor &lt;em&gt;( random state = 1. If the split results in a tie then breaking is deterministic )&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from sklearn.tree import DecisionTreeRegressor

housing_regressor_model = DecisionTreeRegressor(random_state=1)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;(ii)&lt;/strong&gt; Fit the model&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;housing_regressor_model.fit(train_X, train_y)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;step-4-predict&quot;&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Predict&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;predicted_home_prices = housing_regressor_model.predict(val_X)

print(predicted_home_prices)
&lt;/code&gt;&lt;/pre&gt;
&lt;details data-node-type=&quot;hn-details-summary&quot;&gt;
&lt;summary&gt;Output&lt;/summary&gt;
&lt;p&gt;&lt;code&gt;[ 503000. 1857000. 760000. ... 4200000. 800000. 1785000.]&lt;/code&gt;&lt;/p&gt;
&lt;/details&gt;
&lt;h4 id=&quot;step-5-validate&quot;&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; Validate&lt;/h4&gt;
&lt;p&gt;Using the &lt;strong&gt;&lt;em&gt;Mean Absolute Error&lt;/em&gt;&lt;/strong&gt; metric as discussed above.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from sklearn.metrics import mean_absolute_error

mae = mean_absolute_error(val_y, predicted_home_prices)
print(mae)
&lt;/code&gt;&lt;/pre&gt;
&lt;details data-node-type=&quot;hn-details-summary&quot;&gt;
&lt;summary&gt;Output&lt;/summary&gt;
&lt;p&gt;251698.44673983214&lt;/p&gt;
&lt;/details&gt;
&lt;h4 id=&quot;step-6-optimise&quot;&gt;&lt;strong&gt;Step 6:&lt;/strong&gt; Optimise&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;How can we minimise the MAE?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;By using a process known as &lt;strong&gt;Hyperparameter Optimisation&lt;/strong&gt; .&lt;br&gt;
We can tune our decision tree using the &lt;code&gt;max_leaf_nodes&lt;/code&gt; parameter, which is passed to the model before training. This setting allows us to specify the upper limit of leaf nodes the model is allowed to create, helping us control the balance between underfitting (too few leaves) and overfitting (too many leaves).&lt;/p&gt;
&lt;p&gt;Let see if we can find a value for &lt;code&gt;max_leaf_nodes&lt;/code&gt; that minimise the MAE.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;mae_scores = []
candidate_levels = [10, 100, 200, 400, 500, 1000, 5000]

for max_leafs in candidate_levels:
    # Initialize and fit the model with the current candidate size
    model = DecisionTreeRegressor(max_leaf_nodes=max_leafs, random_state=0)
    model.fit(train_X, train_y)
    
    # Predict and evaluate
    preds_val = model.predict(val_X)
    mae = mean_absolute_error(val_y, preds_val)
    
    # Store the result as a sublist: [error, node_count]
    mae_scores.append([mae, max_leafs])
    print(f&quot;Max leaf nodes: {max_leafs} | MAE: {mae:.2f}&quot;)

# Find the sublist with the lowest MAE score
smallest_mae = min(mae_scores, key=lambda x: x[0])
print(f&quot;\nThe optimal choice for max_leaf_nodes is: {smallest_mae[1]} (MAE: {smallest_mae[0]:.2f})&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;details data-node-type=&quot;hn-details-summary&quot;&gt;
&lt;summary&gt;Output&lt;/summary&gt;
&lt;p&gt;&lt;code&gt;Max leaf nodes: 10 | MAE: 320570.21&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 100 | MAE: 256533.25&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 200 | MAE: 244453.42&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 400 | MAE: 243238.90&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 500 | MAE: 241920.26&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 1000 | MAE: 243230.84&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;Max leaf nodes: 5000 | MAE: 256050.02&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;The optimal choice for max_leaf_nodes is: 500 (MAE: 241920.26)&lt;/code&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;
&lt;/details&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/24636/building-decision-trees-with-pandas-and-scikit-learn</guid>
<pubDate>Fri, 14 Aug 2026 14:10:38 +0000</pubDate>
</item>
<item>
<title>Trial by Fire: From Garbage Excel to Relational Graph with Python and Pandas</title>
<link>https://coderlegion.com/15944/trial-by-fire-from-garbage-excel-to-relational-graph-with-python-and-pandas</link>
<description>&lt;h3 id=&quot;1-the-hook-industrial-data-entropy&quot;&gt;1. The Hook: Industrial Data Entropy&lt;/h3&gt;
&lt;p&gt;In standard academic theory, data sets are inherently clean. In the active reality of the industrial supply chain, obsolete ERPs continually export garbage arrays.&lt;/p&gt;
&lt;p&gt;Receiving a flat Bill of Materials systematically exported from a legacy database immediately binds you to processing massive structural entropy: entirely void parameter cells, anomalous blank spacing hidden inside critical part numbers (e.g., &lt;code&gt;&quot; SN74LS00N &quot;&lt;/code&gt;), unstandardized component manufacturer nomenclatures (inconsistently shifting between capitals and disparate acronyms like &quot;ti&quot;), and severe mixed data typing where strict numerals conflict natively with raw text variables.&lt;/p&gt;
&lt;p&gt;Pushing this raw flat algorithmic entropy directly forward into a live relational matrix triggers a complete referential integrity failure. The process inherently requires deploying a clean staging environment.&lt;/p&gt;
&lt;h3 id=&quot;2-the-etl-pipeline-extract-transform-load-&quot;&gt;2. The ETL Pipeline (Extract, Transform, Load)&lt;/h3&gt;
&lt;p&gt;Securing the database perimeter requires a rigorous intermediate layer. We employ &lt;strong&gt;Pandas&lt;/strong&gt;, effectively operating as the strictly objective gatekeeper to our foundational PostgreSQL database.&lt;/p&gt;
&lt;p&gt;Before a solitary piece of hardware telemetry reaches the backend schemas, the dedicated Python layer strictly enforces dataset standardization. We routinely execute hard operations securely using &lt;code&gt;.str.strip()&lt;/code&gt;, &lt;code&gt;.str.title()&lt;/code&gt;, and &lt;code&gt;.fillna()&lt;/code&gt; to properly homogenize external manufacturer part numbers (MPNs), completely delete volatile residual spaces, and explicitly enforce explicit valid ENUM classifications replacing null lifecycle constraints natively prior to API linkage.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def load_and_clean_data(filepath: str) -&amp;gt; pd.DataFrame:
    df = pd.read_csv(filepath)
    
    # 1. Radical space elimination and uppercase standardization (Avoids hardcoding)
    df['Manufacturer_PN'] = df['Manufacturer_PN'].str.strip().str.upper()
    df['Manufacturer'] = df['Manufacturer'].str.strip().str.upper()
    
    # 2. Enforced data typing (Guaranteed numerical quantities)
    df['Quantity_per_Assembly'] = pd.to_numeric(
        df['Quantity_per_Assembly'].astype(str).str.strip(), 
        errors='coerce'
    ).fillna(1).astype(int)
    
    # 3. Containment of missing values
    df['Lifecycle'] = df['Lifecycle'].replace(r'^\s*$', np.nan, regex=True).fillna('Active')
    
    return df
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;3-the-graph-challenge-shattering-the-flat-table-&quot;&gt;3. The Graph Challenge (Shattering the Flat Table)&lt;/h3&gt;
&lt;p&gt;A Bill of Materials mathematically operates internally as a hierarchical tree structure natively, not a flat dimension stack.&lt;/p&gt;
&lt;p&gt;In order to systematically populate the highly restrictive &lt;code&gt;bom_lines&lt;/code&gt; array cleanly avoiding the database exclusive &lt;code&gt;CHECK&lt;/code&gt; integrity blocker explicitly coded earlier, the python automation segregates and systematically separates the initial two-dimensional &lt;em&gt;DataFrame&lt;/em&gt; sequentially into two independent logical grouping vectors.&lt;/p&gt;
&lt;p&gt;Applying this distinct data segmentation strictly ensures the entire tree graphs properly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Loop 1:&lt;/strong&gt; Explicitly tying Final Parent Products (&lt;code&gt;End_Product_SKU&lt;/code&gt;) entirely to specific internal Subassembly containers (&lt;code&gt;Assembly_PN&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Loop 2:&lt;/strong&gt; Structurally tying Internal Subassemblies (&lt;code&gt;Assembly_PN&lt;/code&gt;) strictly natively downward to explicit Base Component items (&lt;code&gt;Component_PN&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This absolute directional differentiation operates cleanly resolving integration faults natively satisfying the mutually exclusive table constraints enforced inside Supabase, correctly mimicking highly accurate factory layout trees algorithmically.&lt;/p&gt;
&lt;h3 id=&quot;4-the-golden-rule-ingestion-idempotency&quot;&gt;4. The Golden Rule: Ingestion Idempotency&lt;/h3&gt;
&lt;p&gt;Before a standard data module successfully reaches enterprise standard operation it strictly requires satisfying system &lt;strong&gt;Idempotency&lt;/strong&gt;. This establishes directly that any localized operations engineer can forcefully execute the extraction module recursively infinite sequential times utilizing identical hardware array data completely strictly avoiding destroying structural records nor accidentally generating unconstrained graph hierarchy duplication.&lt;/p&gt;
&lt;p&gt;Exploiting primitive &lt;code&gt;INSERT&lt;/code&gt; API calls natively corrupts the database integrity by duplicating the graph edges. Instead, the implementation forcefully deploys the &lt;code&gt;upsert()&lt;/code&gt; functions logically integrated seamlessly through the Supabase SDK backend architecture utilizing strictly declared Postgres &lt;code&gt;UNIQUE&lt;/code&gt; keys firmly established systematically across the specific domains (&lt;code&gt;sku&lt;/code&gt; directly crossing global product ranges, &lt;code&gt;internal_pn&lt;/code&gt; binding isolated component IDs, and &lt;code&gt;mpn&lt;/code&gt; natively locking foreign market parts respectively).&lt;/p&gt;
&lt;p&gt;Executing automated telemetry pushes immediately executes cleanly verifying redundant array vectors explicitly reporting live structural compliance seamlessly across loop iterations:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;--- Ingestando Products (Idempotente) ---
Upserted 3 products.
--- Ingestando Internal Parts (Idempotente) ---
Upserted 18 internal parts (assemblies &amp;amp; components).
--- Ingestando Manufacturer Parts Telemetry (Idempotente) ---
Upserted 16 manufacturer external parts.
--- Ingestando AML (Mapeo Interno -&amp;gt; Externo) ---
No new AML links to insert (Idempotent success).
--- Ingestando BOM Lines (Grafo Bidireccional Segregado) ---
Mapeando relaciones: Producto Final -&amp;gt; Subensamblaje...
Mapeando relaciones: Subensamblaje -&amp;gt; Componente...
El Grafo BOM está completamente sincronizado (Idempotent success).

[OK] Migración a entorno relacional completada al 100%.
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;the-sandbox-execute-it-yourself&quot;&gt;The Sandbox: Execute it Yourself&lt;/h4&gt;
&lt;p&gt;In Operations Engineering, code is worth more than theory. I have prepared an interactive and secure environment (Zero Friction) for you to test this ETL pipeline.&lt;/p&gt;
&lt;p&gt;You don't need to install anything or configure databases. The script will spin up an SQL engine in your browser's memory, ingest a corrupt CSV file, cleanse it using Pandas, and build the relational tree in milliseconds, demonstrating idempotency live.&lt;/p&gt;
&lt;p&gt; &lt;a rel=&quot;nofollow&quot; href=&quot;https://colab.research.google.com/drive/1kMLX2RexPSZVHXuXURZ1VnF_w2nRPgxg?usp=sharing&quot;&gt;Access the Interactive Google Colab Here&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;5-closing-amp-cta-towards-the-ai-brain-&quot;&gt;5. Closing &amp;amp; CTA (Towards the AI Brain)&lt;/h3&gt;
&lt;p&gt;The system structural data logic completely establishes pure stability. We strictly transported fundamentally corrupt, stagnant standard tabular Excel files completely across explicit programming loops directly natively injecting refined node values natively filling a vastly superior PostgreSQL relational database firmly.&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;The core foundations remain entirely structural and secure. We possess a natively stable IEC 62402 compliant relational architecture structurally fused directly with a robust Python processing ETL node securely operating live. Crossing into the incoming operational module (Block 3), we firmly awaken complex systematic intelligence cleanly processing logic directly on hardware trees. We deploy strictly scalable Agentic AI parameters (LangChain / CrewAI) comprehensively actively connected inside the unified database constantly autonomously identifying internal financial stress resulting dynamically processing external global EOL silicon alerts. Subscribe consistently witnessing the Agentic Radar launch sequence.&lt;/p&gt;
&lt;/blockquote&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/15944/trial-by-fire-from-garbage-excel-to-relational-graph-with-python-and-pandas</guid>
<pubDate>Mon, 27 Apr 2026 05:59:10 +0000</pubDate>
</item>
<item>
<title>Mastering Pandas — Part 4: Data Visualization with Matplotlib &amp; Seaborn</title>
<link>https://coderlegion.com/13871/mastering-pandas-part-4-data-visualization-with-matplotlib-seaborn</link>
<description>&lt;h3 id=&quot;from-clean-data-to-clear-insight&quot;&gt;From Clean Data to Clear Insight&lt;/h3&gt;
&lt;p&gt;In Part 3, you learned how to clean messy data and combine multiple sources into one unified DataFrame. Now that your data is ready, the next step is to communicate what's inside it — and nothing communicates data faster or more clearly than a chart.&lt;/p&gt;
&lt;p&gt;This article covers the two most important visualization libraries in Python: &lt;strong&gt;Matplotlib&lt;/strong&gt;, the core engine that powers all plotting, and &lt;strong&gt;Seaborn&lt;/strong&gt;, a higher-level library built on top of it that produces beautiful statistical charts with minimal code. By the end, you'll know which tool to reach for depending on what you need to show.&lt;/p&gt;
&lt;p&gt;We'll use this sample dataset throughout:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {
    'Country':         ['China', 'India', 'USA', 'Brazil', 'UK'],
    'Continent':       ['Asia', 'Asia', 'North America', 'South America', 'Europe'],
    '2022 Population': [1412000000, 1380000000, 331000000, 214000000, 67000000],
    'Area (km2)':      [9597000, 3287000, 9834000, 8516000, 243000]
}
df = pd.DataFrame(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;part-1-matplotlib-the-engine&quot;&gt;Part 1 — Matplotlib: The Engine&lt;/h3&gt;
&lt;h4 id=&quot;what-is-matplotlib-&quot;&gt;What is Matplotlib?&lt;/h4&gt;
&lt;p&gt;Matplotlib is the foundational plotting library in Python. Every chart you create in Python — whether through Pandas, Seaborn, or directly — eventually goes through Matplotlib to render the final output. Think of it as the engine: it handles the low-level work of drawing lines, shapes, colors, axes, and text.&lt;/p&gt;
&lt;p&gt;The submodule you'll use in practice is &lt;code&gt;matplotlib.pyplot&lt;/code&gt;, which gives you a clean, high-level interface without managing every visual detail manually:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import matplotlib.pyplot as plt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Matplotlib works across three styles, each suited to a different situation:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Style &lt;/th&gt;&lt;th&gt;When to use&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;df.plot(kind=&quot;bar&quot;, y=&quot;col&quot;)&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Your data is already in a DataFrame — quickest way&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;plt.plot(xs, ys)&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Working with raw lists, arrays, or math functions&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;fig, ax = plt.subplots()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Multiple subplots or full layout control&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;All three ultimately use Matplotlib to render the chart. &lt;code&gt;plt.show()&lt;/code&gt; is always called at the end to display it.&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;global-settings-with-plt-rcparams&quot;&gt;Global Settings with &lt;code&gt;plt.rcParams&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;plt.rcParams&lt;/code&gt; is a global settings dictionary. Any value you set here applies to every chart created afterward in the session — so you set it once at the top of your notebook and never repeat it.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;plt.rcParams['figure.figsize'] = (12, 5)   # default width and height
plt.rcParams['font.size']      = 13         # default font size
plt.rcParams['figure.dpi']     = 100        # image sharpness
plt.rcParams['lines.linewidth'] = 2         # default line thickness
plt.rcParams['axes.grid']      = True       # show grid on all charts
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;setting-a-visual-theme-with-plt-style-use-&quot;&gt;Setting a Visual Theme with &lt;code&gt;plt.style.use()&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;One line changes the entire look of your charts — colors, background, grid style, and fonts. Call it &lt;strong&gt;before&lt;/strong&gt; your plot, not after.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;plt.style.use(&quot;ggplot&quot;)
df.plot(kind=&quot;bar&quot;, y=&quot;2022 Population&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Style &lt;/th&gt;&lt;th&gt;Look&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;ggplot&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Gray background, colored lines — popular R-like style&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;seaborn-v0_8-whitegrid&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Clean, modern, white with grid&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;fivethirtyeight&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Bold, thick lines — news article style&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;dark_background&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Black background&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;bmh&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Soft colors, Bayesian style&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;grayscale&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Shades of gray only&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;tableau-colorblind10&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Colorblind-friendly palette&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Run &lt;code&gt;print(plt.style.available)&lt;/code&gt; to see every available option.&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;plotting-from-a-dataframe-with-plot-&quot;&gt;Plotting from a DataFrame with &lt;code&gt;.plot()&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;Since Pandas is built on Matplotlib, every DataFrame and Series has a &lt;code&gt;.plot()&lt;/code&gt; method that creates a chart in one line.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.plot(kind=&quot;bar&quot;, x=&quot;Country&quot;, y=&quot;2022 Population&quot;, figsize=(10, 5), title=&quot;Population by Country&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;kind=&lt;/code&gt; parameter selects the chart type. All common types are supported:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;&lt;code&gt;kind=&lt;/code&gt; &lt;/th&gt;&lt;th&gt;Chart&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;bar&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Vertical bars&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;barh&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Horizontal bars&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;line&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Line chart (default)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;pie&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Pie chart&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;hist&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Histogram&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;scatter&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Scatter plot&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;&quot;box&quot;&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Box plot&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;You can also call the chart type directly as a method — both styles produce identical output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# These two are exactly the same:
df.plot(kind=&quot;bar&quot;, x=&quot;Country&quot;, y=&quot;2022 Population&quot;)
df.plot.bar(x=&quot;Country&quot;, y=&quot;2022 Population&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The direct method style (&lt;code&gt;df.plot.bar()&lt;/code&gt;) is shorter and more common in practice.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Key parameters you'll use on almost every chart:&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Parameter &lt;/th&gt;&lt;th&gt;What it does &lt;/th&gt;&lt;th&gt;Example&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;kind&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Chart type &lt;/td&gt;&lt;td&gt;&lt;code&gt;&quot;bar&quot;&lt;/code&gt;, &lt;code&gt;&quot;line&quot;&lt;/code&gt;, &lt;code&gt;&quot;scatter&quot;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;x&lt;/code&gt; / &lt;code&gt;y&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Columns for axes &lt;/td&gt;&lt;td&gt;&lt;code&gt;x=&quot;Country&quot;&lt;/code&gt;, &lt;code&gt;y=&quot;2022 Population&quot;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;figsize&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Width and height in inches &lt;/td&gt;&lt;td&gt;&lt;code&gt;figsize=(10, 5)&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;title&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Chart title &lt;/td&gt;&lt;td&gt;&lt;code&gt;title=&quot;Population by Country&quot;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;color&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Bar/line color &lt;/td&gt;&lt;td&gt;&lt;code&gt;color=&quot;steelblue&quot;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;legend&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Show or hide legend &lt;/td&gt;&lt;td&gt;&lt;code&gt;legend=True&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;xlabel&lt;/code&gt; / &lt;code&gt;ylabel&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Axis labels &lt;/td&gt;&lt;td&gt;&lt;code&gt;xlabel=&quot;Country&quot;&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;rot&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Rotation of tick labels &lt;/td&gt;&lt;td&gt;&lt;code&gt;rot=45&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;grid&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Show background grid &lt;/td&gt;&lt;td&gt;&lt;code&gt;grid=True&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;alpha&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Transparency &lt;/td&gt;&lt;td&gt;&lt;code&gt;alpha=0.8&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;bins&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Bin count (histogram only) &lt;/td&gt;&lt;td&gt;&lt;code&gt;bins=20&lt;/code&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.plot(
    kind=&quot;bar&quot;,
    x=&quot;Country&quot;,
    y=&quot;2022 Population&quot;,
    figsize=(10, 5),
    title=&quot;2022 World Population&quot;,
    color=&quot;steelblue&quot;,
    xlabel=&quot;Country&quot;,
    ylabel=&quot;Population&quot;,
    rot=0,
    grid=True,
    alpha=0.85
)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;plotting-directly-with-plt-plot-&quot;&gt;Plotting Directly with &lt;code&gt;plt.plot()&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;When your data is not in a DataFrame — raw lists, NumPy arrays, or a mathematical function — use &lt;code&gt;plt.plot()&lt;/code&gt; directly.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np

xs = np.arange(-5, 5, 0.25)
ys = xs ** 2

plt.figure(figsize=(8, 5))
plt.plot(xs, ys, color=&quot;steelblue&quot;, linewidth=2, linestyle=&quot;--&quot;)
plt.title(&quot;Quadratic Function&quot;)
plt.xlabel(&quot;X&quot;)
plt.ylabel(&quot;Y&quot;)
plt.grid(True)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;Matplotlib doesn't know your data is a curve — it connects the dots you give it with straight lines. When points are closely spaced (as with &lt;code&gt;np.arange&lt;/code&gt; step &lt;code&gt;0.25&lt;/code&gt;), hundreds of short segments visually blend into a smooth curve.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;Customizing &lt;code&gt;plt.plot()&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Color
plt.plot(xs, ys, color='red')

# Line style
plt.plot(xs, ys, linestyle='--')    # dashed
plt.plot(xs, ys, linestyle=':')     # dotted
plt.plot(xs, ys, linestyle='-.')    # dash-dot

# Markers at each point
plt.plot(xs, ys, marker='o')        # circles
plt.plot(xs, ys, marker='s')        # squares
plt.plot(xs, ys, marker='^')        # triangles

# Everything combined
plt.plot(xs, ys, color='green', linestyle='--', linewidth=2, marker='o')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want dots without a line, use &lt;code&gt;plt.scatter()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;plt.scatter(xs, ys)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;decorating-any-chart&quot;&gt;Decorating Any Chart&lt;/h4&gt;
&lt;p&gt;These functions work on any chart — whether drawn through Pandas or directly:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;plt.title(&quot;Chart Title&quot;)
plt.xlabel(&quot;X Axis Label&quot;)
plt.ylabel(&quot;Y Axis Label&quot;)
plt.grid(True)
plt.legend()      # shows labels defined with label= on each line
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When plotting multiple lines, use &lt;code&gt;label=&lt;/code&gt; with each &lt;code&gt;plt.plot()&lt;/code&gt; call, then &lt;code&gt;plt.legend()&lt;/code&gt; to display them:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;ys1 = xs ** 2
ys2 = xs ** 3

plt.plot(xs, ys1, label=&quot;f(x) = x²&quot;)
plt.plot(xs, ys2, label=&quot;f(x) = x³&quot;, linestyle=&quot;--&quot;)
plt.legend()
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;multiple-subplots-with-object-oriented-style&quot;&gt;Multiple Subplots with Object-Oriented Style&lt;/h4&gt;
&lt;p&gt;When you need more than one chart in the same figure, use the object-oriented style. It gives you full control over each subplot independently.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# 1 row, 2 columns — side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))

ax1.bar(df[&quot;Country&quot;], df[&quot;2022 Population&quot;], color=&quot;steelblue&quot;)
ax1.set_title(&quot;Population by Country&quot;)
ax1.set_xlabel(&quot;Country&quot;)
ax1.set_ylabel(&quot;Population&quot;)

ax2.scatter(df[&quot;Area (km2)&quot;], df[&quot;2022 Population&quot;], color=&quot;tomato&quot;)
ax2.set_title(&quot;Area vs Population&quot;)
ax2.set_xlabel(&quot;Area (km²)&quot;)
ax2.set_ylabel(&quot;Population&quot;)

plt.tight_layout()
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;fig&lt;/code&gt; is the whole figure container. &lt;code&gt;ax1&lt;/code&gt; and &lt;code&gt;ax2&lt;/code&gt; are the individual plotting areas. The pattern is the same as &lt;code&gt;plt.*&lt;/code&gt; calls, just moved to &lt;code&gt;ax.set_*()&lt;/code&gt; methods.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;part-2-seaborn-statistical-visualization&quot;&gt;Part 2 — Seaborn: Statistical Visualization&lt;/h3&gt;
&lt;h4 id=&quot;what-is-seaborn-&quot;&gt;What is Seaborn?&lt;/h4&gt;
&lt;p&gt;Seaborn is a library built on top of Matplotlib, designed for statistical data visualization. It produces polished, publication-quality charts with far less code than raw Matplotlib, and works natively with Pandas DataFrames.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import seaborn as sns
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every Seaborn chart follows the same basic structure:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.chart_type(data=df, x='column_name', y='column_name')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;hue=&lt;/code&gt; parameter is Seaborn's most powerful feature — it automatically splits and colors your data by a category column, adding a legend with no extra work:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.scatterplot(data=df, x='Area (km2)', y='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;global-styling-with-set-theme-&quot;&gt;Global Styling with &lt;code&gt;set_theme()&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;Call this once at the top. Every chart afterward follows these settings automatically.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.set_theme(style='whitegrid', palette='deep', font_scale=1.2)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;style&lt;/code&gt;&lt;/strong&gt; controls the background:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.set_theme(style='whitegrid')   # white background with grid — most common
sns.set_theme(style='darkgrid')    # dark background with grid
sns.set_theme(style='white')       # white background, no grid
sns.set_theme(style='ticks')       # minimal, axis ticks only
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;palette&lt;/code&gt;&lt;/strong&gt; controls the colors of chart elements:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.set_theme(palette='deep')        # default, rich colors
sns.set_theme(palette='muted')       # softer, less saturated
sns.set_theme(palette='pastel')      # light pastel colors
sns.set_theme(palette='colorblind')  # accessible for colorblind readers
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;font_scale&lt;/code&gt;&lt;/strong&gt; scales all text up or down:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.set_theme(font_scale=1.5)    # larger text
sns.set_theme(font_scale=0.8)    # smaller text
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To apply a style to one chart only without changing global settings:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;with sns.axes_style('whitegrid'):
    sns.barplot(data=df, x='Continent', y='2022 Population')
    plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To reset everything back to Matplotlib defaults: &lt;code&gt;sns.reset_defaults()&lt;/code&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h4 id=&quot;relational-charts-showing-relationships-between-numbers&quot;&gt;Relational Charts — Showing Relationships Between Numbers&lt;/h4&gt;
&lt;p&gt;Use these when you want to see how two numeric columns relate to each other.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;scatterplot()&lt;/code&gt;&lt;/strong&gt; — each row becomes one dot on the chart:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Basic
sns.scatterplot(data=df, x='Area (km2)', y='2022 Population')

# Colored by continent
sns.scatterplot(data=df, x='Area (km2)', y='2022 Population', hue='Continent')
plt.title(&quot;Area vs Population&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;lineplot()&lt;/code&gt;&lt;/strong&gt; — connects points with a line. Best for time series or ordered data:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.lineplot(data=df, x='Country', y='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;relplot()&lt;/code&gt;&lt;/strong&gt; — a single figure-level function for both scatter and line. Use &lt;code&gt;kind=&lt;/code&gt; to switch:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.relplot(data=df, x='Area (km2)', y='2022 Population', kind='scatter', hue='Continent')
sns.relplot(data=df, x='Country', y='2022 Population', kind='line')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;distribution-charts-showing-how-values-are-spread&quot;&gt;Distribution Charts — Showing How Values Are Spread&lt;/h4&gt;
&lt;p&gt;Use these to understand the shape and spread of a numeric column.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;histplot()&lt;/code&gt;&lt;/strong&gt; — bars showing how many values fall within each range:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Basic histogram
sns.histplot(data=df, x='2022 Population')

# With smooth density curve on top
sns.histplot(data=df, x='2022 Population', kde=True)

# Split by category
sns.histplot(data=df, x='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;kdeplot()&lt;/code&gt;&lt;/strong&gt; — a smooth density curve, more refined than a histogram:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.kdeplot(data=df, x='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For a 2D density plot showing where two numeric columns overlap:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.kdeplot(data=df, x='Area (km2)', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;rugplot()&lt;/code&gt;&lt;/strong&gt; — adds small tick marks along an axis showing where individual data points are. Typically layered on top of a kdeplot:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.kdeplot(data=df, x='2022 Population')
sns.rugplot(data=df, x='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;ecdfplot()&lt;/code&gt;&lt;/strong&gt; — shows the cumulative distribution: what percentage of values fall below each point:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.ecdfplot(data=df, x='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;displot()&lt;/code&gt;&lt;/strong&gt; — one function to rule all distribution charts. Use &lt;code&gt;kind=&lt;/code&gt; to switch:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.displot(data=df, x='2022 Population', kind='hist', hue='Continent')
sns.displot(data=df, x='2022 Population', kind='kde')
sns.displot(data=df, x='2022 Population', kind='ecdf')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;categorical-charts-comparing-groups&quot;&gt;Categorical Charts — Comparing Groups&lt;/h4&gt;
&lt;p&gt;Use these when one axis is a category and the other is numeric.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;barplot()&lt;/code&gt;&lt;/strong&gt; — shows the &lt;strong&gt;mean&lt;/strong&gt; value per category, with confidence interval bars:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.barplot(data=df, x='Continent', y='2022 Population', hue='Continent')
plt.title(&quot;Average Population by Continent&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;Note: &lt;code&gt;barplot()&lt;/code&gt; shows the &lt;em&gt;mean&lt;/em&gt;, not the raw values. If you want raw counts by category, use &lt;code&gt;countplot()&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;countplot()&lt;/code&gt;&lt;/strong&gt; — counts how many rows belong to each category:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.countplot(data=df, x='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;boxplot()&lt;/code&gt;&lt;/strong&gt; — shows median, quartiles, and outliers. A fast way to spot unusual values:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.boxplot(data=df, x='Continent', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;violinplot()&lt;/code&gt;&lt;/strong&gt; — like a boxplot, but also shows the full distribution shape on both sides. More informative for larger datasets:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.violinplot(data=df, x='Continent', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;stripplot()&lt;/code&gt;&lt;/strong&gt; — shows every individual data point as a dot per category. Useful when you want to see actual values rather than a summary:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.stripplot(data=df, x='Continent', y='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;swarmplot()&lt;/code&gt;&lt;/strong&gt; — same as stripplot but repositions overlapping points so each one is visible:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.swarmplot(data=df, x='Continent', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;pointplot()&lt;/code&gt;&lt;/strong&gt; — shows the mean per category as a dot, connected by lines across categories. Good for spotting trends:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.pointplot(data=df, x='Continent', y='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;catplot()&lt;/code&gt;&lt;/strong&gt; — one function for all categorical charts. Use &lt;code&gt;kind=&lt;/code&gt; to switch between them:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.catplot(data=df, x='Continent', y='2022 Population', kind='bar')
sns.catplot(data=df, x='Continent', y='2022 Population', kind='box')
sns.catplot(data=df, x='Continent', y='2022 Population', kind='violin')
sns.catplot(data=df, x='Continent', y='2022 Population', kind='strip')
sns.catplot(data=df, x='Continent', y='2022 Population', kind='swarm')
sns.catplot(data=df, x='Continent', y='2022 Population', kind='point')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;matrix-amp-regression-charts-correlations-and-trends&quot;&gt;Matrix &amp;amp; Regression Charts — Correlations and Trends&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;corr()&lt;/code&gt; + &lt;code&gt;heatmap()&lt;/code&gt;&lt;/strong&gt; — the most common combination for exploring how numeric columns relate to each other:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;corr = df.select_dtypes(include='number').corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title(&quot;Correlation Matrix&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The values range from -1.0 (perfect negative relationship) to 1.0 (perfect positive relationship). &lt;code&gt;annot=True&lt;/code&gt; displays the number inside each cell. &lt;code&gt;cmap='coolwarm'&lt;/code&gt; colors high values red and low values blue.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;clustermap()&lt;/code&gt;&lt;/strong&gt; — same as heatmap but automatically reorders rows and columns by similarity using clustering:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.clustermap(corr, annot=True, cmap='coolwarm')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;pairplot()&lt;/code&gt;&lt;/strong&gt; — creates scatter plots for every combination of numeric columns at once, with distribution plots along the diagonal. The fastest way to get a complete overview of your data:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# All numeric columns
sns.pairplot(df.select_dtypes(include='number'))

# Colored by a category
sns.pairplot(df, hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;jointplot()&lt;/code&gt;&lt;/strong&gt; — shows a scatter plot of two columns, plus the distribution of each column on the margins:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.jointplot(data=df, x='Area (km2)', y='2022 Population')

# With a regression line
sns.jointplot(data=df, x='Area (km2)', y='2022 Population', kind='reg')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;lmplot()&lt;/code&gt;&lt;/strong&gt; — scatter plot with a regression line fitted through the data. Supports separate lines per group:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.lmplot(data=df, x='Area (km2)', y='2022 Population')

# Separate regression line per continent
sns.lmplot(data=df, x='Area (km2)', y='2022 Population', hue='Continent')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;regplot()&lt;/code&gt;&lt;/strong&gt; — the axes-level version of &lt;code&gt;lmplot()&lt;/code&gt;. Does the same thing but doesn't support grouping. Use when you want to embed a regression plot inside a larger figure with subplots:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.regplot(data=df, x='Area (km2)', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;residplot()&lt;/code&gt;&lt;/strong&gt; — shows the residuals of a regression: how far each actual point is from the predicted line. A flat, random scatter around zero means the regression is a good fit:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.residplot(data=df, x='Area (km2)', y='2022 Population')
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;combining-seaborn-with-matplotlib&quot;&gt;Combining Seaborn with Matplotlib&lt;/h4&gt;
&lt;p&gt;Seaborn creates the chart. Matplotlib customizes it. Both work together in the same block — you never have to choose one or the other:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;sns.boxplot(data=df, x='Continent', y='2022 Population', palette='pastel')

plt.title('Population Distribution by Continent')
plt.xlabel('Continent')
plt.ylabel('Population')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is the standard workflow: Seaborn for the chart, Matplotlib for the title, labels, rotation, and layout.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;choosing-the-right-tool&quot;&gt;Choosing the Right Tool&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Use Matplotlib when:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Your data is in raw lists or NumPy arrays, not a DataFrame&lt;/li&gt;
&lt;li&gt;You need multiple subplots in a specific layout&lt;/li&gt;
&lt;li&gt;You want pixel-level control over every visual element&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Use Seaborn when:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Your data is in a DataFrame and ready to visualize&lt;/li&gt;
&lt;li&gt;You want a beautiful chart quickly with minimal code&lt;/li&gt;
&lt;li&gt;You're doing statistical analysis — distributions, correlations, regressions, group comparisons&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In most real projects, you'll use both: Seaborn to draw the chart, Matplotlib to label and polish it.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;GitHub Repo: &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Hu8MA/Mastering-Pandas-Reference&quot;&gt;https://github.com/Hu8MA/Mastering-Pandas-Reference&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Matplotlib Documentation: &lt;a rel=&quot;nofollow&quot; href=&quot;https://matplotlib.org/&quot;&gt;https://matplotlib.org/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Seaborn Documentation: &lt;a rel=&quot;nofollow&quot; href=&quot;https://seaborn.pydata.org/&quot;&gt;https://seaborn.pydata.org/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Pandas Visualization Guide: &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/user_guide/visualization.html&quot;&gt;https://pandas.pydata.org/docs/user_guide/visualization.html&lt;/a&gt;&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/13871/mastering-pandas-part-4-data-visualization-with-matplotlib-seaborn</guid>
<pubDate>Thu, 02 Apr 2026 19:32:22 +0000</pubDate>
</item>
<item>
<title>S&amp;OP: Why Your Excel Is Lying to You (and How to Interrogate It with Python)</title>
<link>https://coderlegion.com/13465/sop-why-your-excel-is-lying-to-you-and-how-to-interrogate-it-with-python</link>
<description>&lt;p&gt;In S&amp;amp;OP (Sales &amp;amp; Operations Planning) meetings, opinions are often discussed instead of facts. &lt;em&gt;&quot;I think we'll sell more&quot;&lt;/em&gt;, &lt;em&gt;&quot;Last month was weird&quot;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The root problem is not the lack of business vision, it's the &lt;strong&gt;lack of signal integrity&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Most supply chains are managed on spreadsheets that accept anything: dates as text, blank spaces, and typos that turn a 100-unit order into 100,000. When you feed your prediction algorithm with that &quot;garbage,&quot; you get amplified garbage (the financial &lt;em&gt;Bullwhip&lt;/em&gt; effect).&lt;/p&gt;
&lt;p&gt;Today we kick off the &lt;strong&gt;S&amp;amp;OP Engineering&lt;/strong&gt; series. We're not going to talk theory; we're going to build a data architecture that audits your business automatically.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://datalaria.com/en/posts/sop_engineering-data-hygiene/cover.png&quot; alt=&quot;S&amp;amp;OP Engineering Image&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;the-problem-signal-to-noise-ratio&quot;&gt;The Problem: Signal-to-Noise Ratio&lt;/h3&gt;
&lt;p&gt;In telecommunications (my original background), noise is any interference that corrupts the signal. In Supply Chain, &quot;noise&quot; is dirty data.&lt;/p&gt;
&lt;p&gt;If you don't filter the noise before planning demand, you're &lt;strong&gt;immobilizing capital&lt;/strong&gt;. An undetected &lt;em&gt;outlier&lt;/em&gt; is money on fire. If your algorithm sees a false spike of 100,000 units, it will order raw materials you don't need, burning cash and taking up warehouse space. Data hygiene is not 'cleaning', it's protecting your operating margin.&lt;/p&gt;
&lt;h4 id=&quot;the-visual-evidence&quot;&gt;The Visual Evidence&lt;/h4&gt;
&lt;p&gt;Before seeing a single line of code, look at the difference between what your ERP exports (top) and the statistical reality of your demand (bottom).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://datalaria.com/en/posts/sop_engineering-data-hygiene/sop_impact_chart.png&quot; alt=&quot;Data Hygiene Impact&quot;&gt;&lt;br&gt;
&lt;em&gt;Top: Raw data with human errors. Bottom: The clean signal ready for AI algorithms.&lt;/em&gt;&lt;/p&gt;
&lt;h3 id=&quot;the-solution-quality-valve-architecture&quot;&gt;The Solution: &quot;Quality Valve&quot; Architecture&lt;/h3&gt;
&lt;p&gt;To solve this, we apply &lt;strong&gt;First Principles Thinking&lt;/strong&gt;. We don't need to &quot;be more careful&quot; with Excel. We need a system that mathematically &lt;strong&gt;prohibits&lt;/strong&gt; the entry of dirty data into our &quot;Single Source of Truth.&quot;&lt;/p&gt;
&lt;p&gt;We've designed an automated pipeline with the following stack:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Brain:&lt;/strong&gt; Python (Pandas + Scipy) for statistical logic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Warehouse:&lt;/strong&gt; Supabase (PostgreSQL) as the &quot;Single Source of Truth.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Agent:&lt;/strong&gt; A script that runs automatically when new files arrive.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;the-code-statistics-gt-intuition&quot;&gt;The Code: Statistics &amp;gt; Intuition&lt;/h4&gt;
&lt;p&gt;We don't use fixed rules (&quot;if greater than 1000, delete&quot;). We use statistics. We implement the &lt;strong&gt;Z-Score&lt;/strong&gt;, which measures how many standard deviations a data point is from the mean.&lt;/p&gt;
&lt;p&gt;If a sale has a &lt;code&gt;Z-Score &amp;gt; 3&lt;/code&gt; (it's more than 3 sigmas from normality), it's mathematically unlikely to be standard behavior. The system doesn't delete it (it could be a real sale), but it &lt;strong&gt;flags it for audit&lt;/strong&gt; and excludes it from automatic prediction.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: We use Z-Score assuming normality to simplify this example. In production scenarios with intermittent demand, we use methods like IQR (Interquartile Range) or MAD (Median Absolute Deviation) which are more robust for non-Gaussian distributions.&lt;/p&gt;
&lt;p&gt;[Image of box plot showing Interquartile Range (IQR) and outliers]&lt;/p&gt;
&lt;p&gt;Here's the core logic from our &lt;code&gt;SupplyChainSanitizer&lt;/code&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def detect_outliers_zscore(self, threshold=3):
    &quot;&quot;&quot;
    Detects statistical anomalies using Z-Score.
    We don't delete the row (info loss), we label it.
    &quot;&quot;&quot;
    # Calculate the standard deviation of the signal
    z_scores = np.abs(stats.zscore(self.df['qty']))
    
    # Flag what is mathematically suspicious
    self.df['is_outlier'] = z_scores &amp;gt; threshold
    return self
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;open-kitchen-try-it-yourself&quot;&gt;Open Kitchen: Try It Yourself&lt;/h3&gt;
&lt;p&gt;As an engineer, I distrust what I can't execute. That's why I've isolated the cleaning logic in an &lt;a rel=&quot;nofollow&quot; href=&quot;https://colab.research.google.com/drive/13BxVyaw46BYWGz8LQQ4WE83KGrQf79jJ?usp=sharing&quot;&gt;interactive Colab Notebook&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;You don't need to install Python or configure databases. I've prepared an ephemeral environment where you can:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Generate a corrupt sales dataset (simulated).&lt;/li&gt;
&lt;li&gt;Run the &lt;code&gt;SupplyChainSanitizer&lt;/code&gt; cleaning engine.&lt;/li&gt;
&lt;li&gt;See how the algorithm detects and separates the noise.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Click the button, hit &quot;Play&quot; on the cells, and observe data engineering in action.&lt;/p&gt;
&lt;h3 id=&quot;production-architecture-behind-the-scenes-&quot;&gt;Production Architecture (Behind the Scenes)&lt;/h3&gt;
&lt;p&gt;For technical profiles interested in how this scales in a real company (Datalaria Core):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Ingestion:&lt;/strong&gt; CSVs are uploaded to a private Bucket in Supabase Storage or a local database.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trigger:&lt;/strong&gt; A Python worker detects the file.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Processing:&lt;/strong&gt; Executes the cleaning in memory (Docker Container).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Persistence:&lt;/strong&gt; Clean data is injected into PostgreSQL using Row Level Security (RLS) to ensure nobody can manually alter the financial history.&lt;/li&gt;
&lt;/ul&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Security Note:&lt;/strong&gt; In production, we never connect scripts with superuser permissions. We use specific Service Roles and strict RLS policies to ensure supply chain integrity.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h4 id=&quot;data-flow-visualization&quot;&gt;Data Flow Visualization&lt;/h4&gt;
&lt;p&gt;The following diagram shows how &quot;dirty&quot; data passes through our &lt;strong&gt;Quality Valve&lt;/strong&gt; before reaching the Single Source of Truth:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://datalaria.com/en/posts/sop_engineering-data-hygiene/sop_part1_diagram.png&quot; alt=&quot;S&amp;amp;OP Engineering Image&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Legend:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Red:&lt;/strong&gt; Raw data with noise (the problem)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Green:&lt;/strong&gt; Clean signal ready for prediction&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Orange:&lt;/strong&gt; Anomalies labeled for human review&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blue:&lt;/strong&gt; Centralized warehouse (Supabase)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;next-step-scientific-prediction&quot;&gt;Next Step: Scientific Prediction&lt;/h3&gt;
&lt;p&gt;Now that we have a clean database (a pure signal), we're ready to look into the future.&lt;/p&gt;
&lt;p&gt;In the next chapter of the series, we'll connect this clean table with &lt;strong&gt;Facebook Prophet&lt;/strong&gt; to generate probabilistic demand forecasts, forever abandoning Excel's simple moving averages.&lt;/p&gt;
&lt;p&gt;Subscribe to receive Chapter 2: &lt;em&gt;&quot;Demand Planning: From Guessing to Probability&quot;&lt;/em&gt;.&lt;/p&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/13465/sop-why-your-excel-is-lying-to-you-and-how-to-interrogate-it-with-python</guid>
<pubDate>Wed, 25 Mar 2026 07:22:37 +0000</pubDate>
</item>
<item>
<title>Mastering Pandas — Part 3: Data Cleaning, Merging &amp; Joining</title>
<link>https://coderlegion.com/13151/mastering-pandas-part-3-data-cleaning-merging-joining</link>
<description>&lt;h3 id=&quot;real-data-is-never-clean&quot;&gt;Real Data Is Never Clean&lt;/h3&gt;
&lt;p&gt;In Part 2, you learned how to group and slice a DataFrame with precision. But in real projects, the data you receive rarely arrives ready to analyze. Column names have spaces. Ages are negative. Phone numbers mix letters with digits. Duplicate rows sneak in. And your data often lives across multiple files that need to be combined before you can do anything useful.&lt;/p&gt;
&lt;p&gt;This article covers the two skills that bridge raw data and real analysis:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Data Cleaning&lt;/strong&gt; — detecting and fixing everything wrong with your data before it corrupts your results&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Merging &amp;amp; Joining&lt;/strong&gt; — combining separate DataFrames into a single, unified dataset&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These topics flow naturally into each other. You clean each source first, then you combine them. That's the order every data analyst follows in practice — and it's the order we'll follow here.&lt;/p&gt;
&lt;p&gt;We'll use this sample dataset throughout the cleaning section:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd
import numpy as np

data = {
    &quot;Name&quot;:             [&quot;Alice&quot;, &quot;bob&quot;, &quot;Carol&quot;, &quot;Alice&quot;, &quot;  dave  &quot;, &quot;Eve&quot;],
    &quot;Age&quot;:              [25, -5, 200, 25, 30, None],
    &quot;Phone&quot;:            [&quot;055-123-4567&quot;, None, &quot;55123x&quot;, &quot;055-123-4567&quot;, &quot;055-987-0000&quot;, &quot;055abc&quot;],
    &quot;Email&quot;:            [&quot;*Emails are not allowed*&quot;, &quot;*Emails are not allowed*&quot;, None, &quot;*Emails are not allowed*&quot;, &quot;*Emails are not allowed*&quot;, &quot;not-an-email&quot;],
    &quot;Paying_Customer&quot;:  [&quot;Y&quot;, &quot;N&quot;, &quot;Yes&quot;, &quot;Y&quot;, &quot;N&quot;, &quot;y&quot;],
    &quot;Score&quot;:            [85, 110, 72, 85, -10, 90],
}
df = pd.DataFrame(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-1-inspect-before-you-touch-anything&quot;&gt;Step 1 — Inspect Before You Touch Anything&lt;/h3&gt;
&lt;p&gt;The most important rule in data cleaning: &lt;strong&gt;look before you act&lt;/strong&gt;. Jumping straight into fixes without understanding the full picture leads to mistakes you won't catch until much later.&lt;/p&gt;
&lt;p&gt;These are the inspection tools you should run on every new dataset:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.shape          # (rows, columns) — how big is this?
df.info()         # column names, data types, non-null counts
df.head()         # first 5 rows
df.tail()         # last 5 rows
df.describe()     # min, max, mean, std — spot impossible values here
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For missing values specifically:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.isna().sum()           # count NaN per column
df.isnull().sum()         # same as isna() — both work
df[df[&quot;Phone&quot;].notna()]   # rows that actually have a phone number
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For duplicates and inconsistent categories:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.duplicated()                         # True/False per row
df[df.duplicated()]                     # show only the duplicate rows
df[&quot;Paying_Customer&quot;].value_counts()    # reveals: Y, N, Yes, y — all meaning the same thing
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Always run &lt;code&gt;describe()&lt;/code&gt; on numeric columns&lt;/strong&gt; — the min and max alone will tell you immediately if something is wrong. A minimum age of -5 or a score of 110 out of 100 is a red flag you can't miss.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-2-fix-column-names-first&quot;&gt;Step 2 — Fix Column Names First&lt;/h3&gt;
&lt;p&gt;Messy column names make everything harder. Clean them before anything else, so every subsequent operation uses predictable, consistent names.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Rename specific columns:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.rename(columns={&quot;Old Name&quot;: &quot;New_Name&quot;, &quot;phone number&quot;: &quot;Phone&quot;})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Clean all column names at once — the standard one-liner:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.columns = df.columns.str.strip().str.lower().str.replace(&quot; &quot;, &quot;_&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This strips surrounding spaces, converts to lowercase, and replaces spaces with underscores in a single chain. After this, &lt;code&gt;&quot;First Name&quot;&lt;/code&gt; becomes &lt;code&gt;&quot;first_name&quot;&lt;/code&gt;, &lt;code&gt;&quot;  Age &quot;&lt;/code&gt; becomes &lt;code&gt;&quot;age&quot;&lt;/code&gt;, and so on.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Before:              After:
&quot;First Name&quot;    →    &quot;first_name&quot;
&quot;  Age &quot;        →    &quot;age&quot;
&quot;Phone Number&quot;  →    &quot;phone_number&quot;
&quot;ZIP Code&quot;      →    &quot;zip_code&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-3-handle-missing-values&quot;&gt;Step 3 — Handle Missing Values&lt;/h3&gt;
&lt;p&gt;Missing values appear as &lt;code&gt;NaN&lt;/code&gt; in Pandas. Before deciding what to do with them, you need to understand &lt;em&gt;why&lt;/em&gt; they're missing — because the right fix depends on the cause.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fill missing values with a fixed value:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Phone&quot;].fillna(&quot;000-000-0000&quot;)    # placeholder for missing phone
df[&quot;Age&quot;].fillna(0)                   # fill numeric with 0
df[&quot;Name&quot;].fillna(&quot;Unknown&quot;)          # fill text with label
df[&quot;Score&quot;].fillna(df[&quot;Score&quot;].mean()) # fill with column average
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Fill missing numeric values by estimating from neighbors:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Sales&quot;] = df[&quot;Sales&quot;].interpolate()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;interpolate()&lt;/code&gt; fills NaN by calculating the midpoint between the values above and below it. This is ideal for time series or sensor data where values change gradually — it would be wrong to use for random datasets.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Before:     After interpolate():
100         100
NaN    →    150   ← estimated midpoint
200         200
NaN    →    225   ← estimated midpoint
250         250
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Remove rows with missing values:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.dropna()                            # drop any row with at least one NaN
df.dropna(subset=[&quot;Phone&quot;])            # drop only if Phone is NaN
df.dropna(thresh=3)                    # drop rows that have fewer than 3 non-NaN values
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;inplace&lt;/code&gt; rule:&lt;/strong&gt; use either &lt;code&gt;inplace=True&lt;/code&gt; or variable assignment — never both. They do the same thing, and combining them produces a bug where &lt;code&gt;df&lt;/code&gt; becomes &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.dropna(subset=[&quot;Phone&quot;], inplace=True)   # ✅ modifies df directly
df = df.dropna(subset=[&quot;Phone&quot;])            # ✅ returns new df
df = df.dropna(subset=[&quot;Phone&quot;], inplace=True)  # ❌ df becomes None
&lt;/code&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-4-remove-duplicates&quot;&gt;Step 4 — Remove Duplicates&lt;/h3&gt;
&lt;p&gt;Duplicate rows silently inflate counts, averages, and totals. Always check for them.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.drop_duplicates()                         # remove fully identical rows
df.drop_duplicates(subset=[&quot;Name&quot;])          # remove rows with duplicate Name only
df.drop_duplicates(subset=[&quot;Name&quot;, &quot;Email&quot;]) # remove rows where both columns match
df.drop_duplicates(keep=&quot;last&quot;)              # keep the last occurrence instead of the first
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Before:                        After drop_duplicates():
Name   Email                   Name   Email
Alice  *Emails are not allowed*          Alice  *Emails are not allowed*
Bob    *Emails are not allowed*      →     Bob    *Emails are not allowed*
Alice  *Emails are not allowed* ← dup    Carol  *Emails are not allowed*
Carol  *Emails are not allowed*
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-5-fix-data-types&quot;&gt;Step 5 — Fix Data Types&lt;/h3&gt;
&lt;p&gt;Pandas sometimes reads numeric columns as strings, or dates as plain text. Operations on wrong types either crash or silently produce wrong results.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Change column type directly:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Zip_Code&quot;] = df[&quot;Zip_Code&quot;].astype(str)     # treat as text, not a number
df[&quot;Age&quot;] = df[&quot;Age&quot;].astype(int)               # convert to integer
df[&quot;Price&quot;] = df[&quot;Price&quot;].astype(float)         # convert to decimal
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Handle messy numbers that contain symbols or text:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Price&quot;] = pd.to_numeric(df[&quot;Price&quot;], errors=&quot;coerce&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;errors=&quot;coerce&quot;&lt;/code&gt; converts anything that can't be parsed into &lt;code&gt;NaN&lt;/code&gt; instead of crashing. This is the safe way to clean columns like &lt;code&gt;&quot;$1,200&quot;&lt;/code&gt; or &lt;code&gt;&quot;N/A&quot;&lt;/code&gt; that can't be directly cast with &lt;code&gt;astype()&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Before:           After pd.to_numeric(..., errors=&quot;coerce&quot;):
&quot;1200&quot;    →       1200.0
&quot;$850&quot;    →       NaN     ← couldn't parse
&quot;700.5&quot;   →       700.5
&quot;N/A&quot;     →       NaN     ← couldn't parse
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Convert to datetime:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;])
df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;], format=&quot;%d/%m/%Y&quot;)  # specify format if needed
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once a column is proper datetime, you unlock sorting by date, filtering by year/month, calculating time differences, and much more.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-6-clean-strings&quot;&gt;Step 6 — Clean Strings&lt;/h3&gt;
&lt;p&gt;String columns are almost always the messiest part of a real dataset. Pandas provides a full &lt;code&gt;.str&lt;/code&gt; accessor with everything you need.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Strip unwanted characters from edges:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Name&quot;] = df[&quot;Name&quot;].str.strip()           # remove spaces from both sides
df[&quot;Name&quot;] = df[&quot;Name&quot;].str.strip(&quot; ./-&quot;)     # remove spaces, dots, slashes, dashes
df[&quot;Name&quot;] = df[&quot;Name&quot;].str.lstrip()          # left side only
df[&quot;Name&quot;] = df[&quot;Name&quot;].str.rstrip()          # right side only
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Replace characters anywhere in the string:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Phone&quot;] = df[&quot;Phone&quot;].str.replace(r&quot;[a-zA-Z]&quot;, &quot;&quot;, regex=True)   # remove all letters
df[&quot;Phone&quot;] = df[&quot;Phone&quot;].str.replace(r&quot;\D&quot;, &quot;&quot;, regex=True)          # keep digits only
df[&quot;Name&quot;]  = df[&quot;Name&quot;].str.replace(r&quot;[./]&quot;, &quot;&quot;, regex=True)         # remove dots and slashes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Standardize text case:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Name&quot;] = df[&quot;Name&quot;].str.lower()     # all lowercase → &quot;alice&quot;
df[&quot;Name&quot;] = df[&quot;Name&quot;].str.upper()     # all uppercase → &quot;ALICE&quot;
df[&quot;Name&quot;] = df[&quot;Name&quot;].str.title()     # title case    → &quot;Alice&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Check text content:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[df[&quot;Email&quot;].str.contains(&quot;@&quot;)]           # filter valid-looking emails
df[df[&quot;Phone&quot;].str.len() != 12]             # find rows where phone length is wrong
df[df[&quot;Name&quot;].str.startswith(&quot;A&quot;)]          # names starting with A
df[df[&quot;Name&quot;].str.endswith(&quot;e&quot;)]            # names ending with e
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Extract a pattern using regex:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Zip&quot;] = df[&quot;Address&quot;].str.extract(r&quot;(\d{5})&quot;)        # pull 5-digit zip code
df[&quot;Area_Code&quot;] = df[&quot;Phone&quot;].str.extract(r&quot;^(\d{3})&quot;)   # pull first 3 digits
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Split one column into multiple columns:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[[&quot;Street&quot;, &quot;State&quot;, &quot;Zip&quot;]] = (
    df[&quot;Address&quot;]
    .str.split(&quot;,&quot;, n=2, expand=True)
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;n=2&lt;/code&gt; limits the split to 2 times, producing exactly 3 parts regardless of how many commas the string contains. &lt;code&gt;expand=True&lt;/code&gt; spreads those parts into separate columns.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-plaintext&quot;&gt;Before:                              After:
&quot;123 Main St, Texas, 75001&quot;   →   Street=&quot;123 Main St&quot;  State=&quot;Texas&quot;  Zip=&quot;75001&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;step-7-replace-and-standardize-values&quot;&gt;Step 7 — Replace and Standardize Values&lt;/h3&gt;
&lt;p&gt;Raw data often has the same value written multiple ways: &lt;code&gt;&quot;Y&quot;&lt;/code&gt;, &lt;code&gt;&quot;Yes&quot;&lt;/code&gt;, &lt;code&gt;&quot;yes&quot;&lt;/code&gt;, &lt;code&gt;&quot;y&quot;&lt;/code&gt; — all meaning the same thing. Standardize them.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Replace whole cell values using a dictionary:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Status&quot;] = df[&quot;Status&quot;].replace({&quot;Y&quot;: &quot;Yes&quot;, &quot;N&quot;: &quot;No&quot;, &quot;y&quot;: &quot;Yes&quot;})

# Apply to multiple columns at once
df[[&quot;Paying_Customer&quot;, &quot;Do_Not_Contact&quot;]] = (
    df[[&quot;Paying_Customer&quot;, &quot;Do_Not_Contact&quot;]]
    .replace({&quot;Y&quot;: &quot;Yes&quot;, &quot;N&quot;: &quot;No&quot;, &quot;y&quot;: &quot;Yes&quot;, &quot;n&quot;: &quot;No&quot;})
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Overwrite invalid values using &lt;code&gt;loc[]&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.loc[df[&quot;Age&quot;] &amp;lt; 0,   &quot;Age&quot;] = None     # negative age → invalid
df.loc[df[&quot;Age&quot;] &amp;gt; 120, &quot;Age&quot;] = None     # age over 120 → invalid
df.loc[df[&quot;Price&quot;] &amp;lt; 0, &quot;Price&quot;] = None   # negative price → invalid
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Keep valid values, replace everything else with NaN:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[&quot;Salary&quot;] = df[&quot;Salary&quot;].where(df[&quot;Salary&quot;] &amp;gt; 0)
# Rows where Salary &amp;lt;= 0 become NaN; the rest are untouched
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;now-combine-merging-amp-joining-dataframes&quot;&gt;Now Combine — Merging &amp;amp; Joining DataFrames&lt;/h3&gt;
&lt;p&gt;Once each source is clean, the next challenge is combining them. In the real world, data almost never lives in a single file. You might have orders in one table, customers in another, and products in a third. Merging is how you bring those pieces together.&lt;/p&gt;
&lt;p&gt;Pandas provides three main tools for this:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Tool &lt;/th&gt;&lt;th&gt;What it does&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;merge()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Joins two DataFrames by matching on a shared column&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;concat()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Stacks DataFrames vertically or side by side&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;join()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Joins on the index instead of a column&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;We'll use these two DataFrames for all the examples:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;customers = pd.DataFrame({
    &quot;ID&quot;:        [1, 2, 3, 4],
    &quot;Name&quot;:      [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Carol&quot;, &quot;Dave&quot;],
    &quot;Country&quot;:   [&quot;USA&quot;, &quot;UK&quot;, &quot;India&quot;, &quot;USA&quot;],
})

orders = pd.DataFrame({
    &quot;ID&quot;:        [1, 2, 3, 5],
    &quot;Product&quot;:   [&quot;Laptop&quot;, &quot;Phone&quot;, &quot;Tablet&quot;, &quot;Monitor&quot;],
    &quot;Price&quot;:     [1200, 800, 600, 400],
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that &lt;code&gt;ID=4&lt;/code&gt; (Dave) exists in &lt;code&gt;customers&lt;/code&gt; but not in &lt;code&gt;orders&lt;/code&gt;, and &lt;code&gt;ID=5&lt;/code&gt; exists in &lt;code&gt;orders&lt;/code&gt; but not in &lt;code&gt;customers&lt;/code&gt;. This is exactly the kind of mismatch you encounter in practice — and why the &lt;code&gt;how=&lt;/code&gt; parameter matters so much.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;1-merge-the-main-tool&quot;&gt;1️⃣ &lt;code&gt;merge()&lt;/code&gt; — The Main Tool&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;merge()&lt;/code&gt; works like a SQL JOIN. It aligns two DataFrames by finding rows where a shared column has the same value.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Basic syntax:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;customers.merge(orders, how=&quot;inner&quot;, on=&quot;ID&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;the-how-parameter-all-four-types&quot;&gt;The &lt;code&gt;how=&lt;/code&gt; Parameter — All Four Types&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# INNER → only rows that match in both DataFrames (default)
customers.merge(orders, how=&quot;inner&quot;, on=&quot;ID&quot;)
# Result: IDs 1, 2, 3 only — Dave (4) and Monitor (5) are excluded

# LEFT → all rows from the left + matched rows from the right
customers.merge(orders, how=&quot;left&quot;, on=&quot;ID&quot;)
# Result: all 4 customers — Dave gets NaN for Product and Price

# RIGHT → all rows from the right + matched rows from the left
customers.merge(orders, how=&quot;right&quot;, on=&quot;ID&quot;)
# Result: all 4 orders — Monitor (ID=5) gets NaN for Name and Country

# OUTER → all rows from both, NaN where no match
customers.merge(orders, how=&quot;outer&quot;, on=&quot;ID&quot;)
# Result: all 5 unique IDs — gaps filled with NaN on both sides
&lt;/code&gt;&lt;/pre&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;&lt;code&gt;how=&lt;/code&gt; &lt;/th&gt;&lt;th&gt;Keeps from Left &lt;/th&gt;&lt;th&gt;Keeps from Right &lt;/th&gt;&lt;th&gt;NaN Possible&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;inner&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Matched only &lt;/td&gt;&lt;td&gt;Matched only &lt;/td&gt;&lt;td&gt;No&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;left&lt;/code&gt; &lt;/td&gt;&lt;td&gt;All rows &lt;/td&gt;&lt;td&gt;Matched only &lt;/td&gt;&lt;td&gt;Right side&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;right&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Matched only &lt;/td&gt;&lt;td&gt;All rows &lt;/td&gt;&lt;td&gt;Left side&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;outer&lt;/code&gt; &lt;/td&gt;&lt;td&gt;All rows &lt;/td&gt;&lt;td&gt;All rows &lt;/td&gt;&lt;td&gt;Both sides&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;CROSS merge — every row with every row:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;customers.merge(orders, how=&quot;cross&quot;)
# Produces 4 × 4 = 16 rows — every customer paired with every order
# No on= parameter — it will raise an error if you include it
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;the-on-parameter-what-to-match-on&quot;&gt;The &lt;code&gt;on=&lt;/code&gt; Parameter — What to Match On&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Match on a single column
customers.merge(orders, how=&quot;inner&quot;, on=&quot;ID&quot;)

# Match on multiple columns — both must match simultaneously
customers.merge(orders, how=&quot;inner&quot;, on=[&quot;ID&quot;, &quot;Country&quot;])

# Auto-detect — Pandas finds all shared column names automatically
customers.merge(orders)
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Be careful with auto-detect.&lt;/strong&gt; If both DataFrames happen to share a column that you don't intend to join on (like a generic &lt;code&gt;&quot;Name&quot;&lt;/code&gt; column), Pandas will include it in the match condition and produce unexpected results. Explicit is safer.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h4 id=&quot;handling-shared-column-names-x-and-y&quot;&gt;Handling Shared Column Names — &lt;code&gt;_x&lt;/code&gt; and &lt;code&gt;_y&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;If both DataFrames have a column with the same name, but you only join on &lt;code&gt;ID&lt;/code&gt;, Pandas keeps both copies and renames them automatically:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Both DataFrames have a &quot;Name&quot; column, but you only merge on &quot;ID&quot;
customers.merge(orders, how=&quot;inner&quot;, on=&quot;ID&quot;)
# Result: Name_x (from customers), Name_y (from orders)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Three ways to fix this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Option 1 — merge on all shared columns so no duplicates appear
customers.merge(orders, how=&quot;inner&quot;, on=[&quot;ID&quot;, &quot;Name&quot;])

# Option 2 — use custom suffixes instead of _x and _y
customers.merge(orders, how=&quot;inner&quot;, on=&quot;ID&quot;, suffixes=(&quot;_customer&quot;, &quot;_order&quot;))

# Option 3 — drop the shared column from one DataFrame before merging
orders_clean = orders.drop(columns=[&quot;Name&quot;])
customers.merge(orders_clean, how=&quot;inner&quot;, on=&quot;ID&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;other-useful-parameters&quot;&gt;Other Useful Parameters&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# left_on / right_on — when the key column has different names in each DataFrame
customers.merge(orders, how=&quot;inner&quot;, left_on=&quot;CustomerID&quot;, right_on=&quot;OrderID&quot;)

# indicator — adds a column showing where each row came from
customers.merge(orders, how=&quot;outer&quot;, on=&quot;ID&quot;, indicator=True)
# _merge column values: &quot;left_only&quot;, &quot;right_only&quot;, &quot;both&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;indicator=True&lt;/code&gt; parameter is especially useful for auditing: after a merge, you can immediately see which rows matched, which came only from the left, and which came only from the right.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;2-concat-stacking-dataframes&quot;&gt;2️⃣ &lt;code&gt;concat()&lt;/code&gt; — Stacking DataFrames&lt;/h3&gt;
&lt;p&gt;While &lt;code&gt;merge()&lt;/code&gt; combines DataFrames horizontally by matching values, &lt;code&gt;concat()&lt;/code&gt; simply stacks them — either rows on top of rows, or columns side by side.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;pd.concat([df1, df2])        # stack vertically (default)
pd.concat([df1, df2], axis=1)  # stack horizontally
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;axis-parameter&quot;&gt;&lt;code&gt;axis=&lt;/code&gt; Parameter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# axis=0 → stack rows vertically (append one DataFrame below another)
monthly_data = pd.concat([january, february, march], axis=0)

# axis=1 → stack columns side by side
combined = pd.concat([names_df, scores_df], axis=1)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;join-parameter&quot;&gt;&lt;code&gt;join=&lt;/code&gt; Parameter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# outer (default) → keep all columns, NaN where a column doesn't exist in one source
pd.concat([df1, df2], join=&quot;outer&quot;)

# inner → keep only columns that exist in all DataFrames
pd.concat([df1, df2], join=&quot;inner&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;ignore-index-parameter&quot;&gt;&lt;code&gt;ignore_index=&lt;/code&gt; Parameter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Without ignore_index — original indices are preserved, which can repeat
pd.concat([df1, df2])
# Index: 0, 1, 2, 0, 1, 2  ← 0, 1, 2 repeats

# With ignore_index=True — fresh sequential index
pd.concat([df1, df2], ignore_index=True)
# Index: 0, 1, 2, 3, 4, 5  ← clean
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Always use &lt;code&gt;ignore_index=True&lt;/code&gt; after stacking unless you specifically need the original indices.&lt;/p&gt;
&lt;h4 id=&quot;keys-parameter&quot;&gt;&lt;code&gt;keys=&lt;/code&gt; Parameter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Label each source so you can identify where each row came from
combined = pd.concat([df1, df2], keys=[&quot;source_a&quot;, &quot;source_b&quot;])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This creates a MultiIndex where the first level is your label and the second is the original row index — useful when you need to trace data back to its source after combining.&lt;/p&gt;
&lt;h4 id=&quot;verify-integrity-parameter&quot;&gt;&lt;code&gt;verify_integrity=&lt;/code&gt; Parameter&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Raises an error if any duplicate index values are found after concatenation
pd.concat([df1, df2], verify_integrity=True)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;merge-vs-concat-when-to-use-which&quot;&gt;&lt;code&gt;merge()&lt;/code&gt; vs &lt;code&gt;concat()&lt;/code&gt; — When to Use Which&lt;/h4&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;code&gt;merge()&lt;/code&gt; &lt;/th&gt;&lt;th&gt;&lt;code&gt;concat()&lt;/code&gt;&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Direction &lt;/td&gt;&lt;td&gt;Horizontal (by matching) &lt;/td&gt;&lt;td&gt;Vertical or horizontal (by stacking)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Needs a shared key column &lt;/td&gt;&lt;td&gt;Yes &lt;/td&gt;&lt;td&gt;No&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Best for &lt;/td&gt;&lt;td&gt;Joining related tables &lt;/td&gt;&lt;td&gt;Combining same-structure data&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Equivalent to &lt;/td&gt;&lt;td&gt;SQL JOIN &lt;/td&gt;&lt;td&gt;SQL UNION&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A simple rule: if you're &lt;strong&gt;combining columns from different tables&lt;/strong&gt;, use &lt;code&gt;merge()&lt;/code&gt;. If you're &lt;strong&gt;stacking more rows of the same structure&lt;/strong&gt;, use &lt;code&gt;concat()&lt;/code&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;3-join-index-based-joining&quot;&gt;3️⃣ &lt;code&gt;join()&lt;/code&gt; — Index-Based Joining&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;join()&lt;/code&gt; works like &lt;code&gt;merge()&lt;/code&gt;, but it joins on the &lt;strong&gt;index&lt;/strong&gt; instead of a regular column. You need to set the index first.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;customers_indexed = customers.set_index(&quot;ID&quot;)
orders_indexed    = orders.set_index(&quot;ID&quot;)

customers_indexed.join(orders_indexed, how=&quot;inner&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;how=&lt;/code&gt; options are the same as &lt;code&gt;merge()&lt;/code&gt;: &lt;code&gt;inner&lt;/code&gt;, &lt;code&gt;left&lt;/code&gt;, &lt;code&gt;right&lt;/code&gt;, &lt;code&gt;outer&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;why-merge-is-almost-always-better&quot;&gt;Why &lt;code&gt;merge()&lt;/code&gt; Is Almost Always Better&lt;/h4&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;code&gt;merge()&lt;/code&gt; &lt;/th&gt;&lt;th&gt;&lt;code&gt;join()&lt;/code&gt;&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Join on any column &lt;/td&gt;&lt;td&gt;✅ Yes &lt;/td&gt;&lt;td&gt;❌ No — index only&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Join on index &lt;/td&gt;&lt;td&gt;✅ Yes &lt;/td&gt;&lt;td&gt;✅ Yes&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Requires &lt;code&gt;set_index()&lt;/code&gt; first &lt;/td&gt;&lt;td&gt;❌ No &lt;/td&gt;&lt;td&gt;✅ Yes&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Simpler syntax &lt;/td&gt;&lt;td&gt;✅ Yes &lt;/td&gt;&lt;td&gt;⚠️ Extra steps&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3 id=&quot;-gt-use-join-only-when-your-data-is-already-indexed-for-example-after-a-groupby-that-produced-a-meaningful-index-otherwise-merge-is-cleaner-and-more-flexible-&quot;&gt;&amp;gt; Use &lt;code&gt;join()&lt;/code&gt; only when your data is already indexed — for example, after a &lt;code&gt;groupby()&lt;/code&gt; that produced a meaningful index. Otherwise, &lt;code&gt;merge()&lt;/code&gt; is cleaner and more flexible.&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;This is Part 3 of the Pandas for Data Science series. Next up: Part 4 — Data Visualization with &lt;strong&gt;Matplotlib &amp;amp; Seaborn&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;To access the full article, please visit the link below or directly access the repository via the links below.&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;Refrences&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;GitHub Repo : &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Hu8MA/Mastering-Pandas-Reference&quot;&gt;https://github.com/Hu8MA/Mastering-Pandas-Reference&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Website : &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/&quot;&gt;https://pandas.pydata.org/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GitHub Library : &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/pandas-dev/pandas&quot;&gt;https://github.com/pandas-dev/pandas&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Course : &lt;a rel=&quot;nofollow&quot; href=&quot;https://youtu.be/Mdq1WWSdUtw&quot;&gt;https://youtu.be/Mdq1WWSdUtw&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Full article : &lt;a rel=&quot;nofollow&quot; href=&quot;https://hussein16mahdi.medium.com/mastering-pandas-part-3-data-cleaning-merging-joining-817a070147ca&quot;&gt;https://hussein16mahdi.medium.com/mastering-pandas-part-3-data-cleaning-merging-joining-817a070147ca&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/13151/mastering-pandas-part-3-data-cleaning-merging-joining</guid>
<pubDate>Wed, 18 Mar 2026 23:24:55 +0000</pubDate>
</item>
<item>
<title>Mastering Pandas — Part 1: Reading, Sorting &amp; Displaying Data</title>
<link>https://coderlegion.com/12225/mastering-pandas-part-1-reading-sorting-displaying-data</link>
<description>&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Pandas for Data Science Series — Article #1&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h3 id=&quot;what-is-pandas-and-why-does-it-matter-&quot;&gt;What is Pandas and Why Does It Matter?&lt;/h3&gt;
&lt;p&gt;Pandas is an open-source Python library built specifically for data manipulation and analysis. Released in 2008 and named after &quot;Panel Data&quot; — a term from econometrics — it has since become one of the most essential tools in the entire Python ecosystem.&lt;/p&gt;
&lt;p&gt;At its core, Pandas gives you two powerful data structures:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Series&lt;/strong&gt; — a single column of data&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DataFrame&lt;/strong&gt; — a full table with rows and columns (think of it as a turbocharged spreadsheet you control with code)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Whether you're working in &lt;strong&gt;data science, machine learning, financial analysis, or business intelligence&lt;/strong&gt;, chances are you'll be loading, exploring, and transforming data with Pandas before you do anything else. It integrates seamlessly with libraries like NumPy, Matplotlib, Seaborn, Scikit-learn, and TensorFlow, making it the essential starting point in nearly every data workflow.&lt;/p&gt;
&lt;p&gt;In this first article of the series, you'll cover two essential skill sets: &lt;strong&gt;reading data into Pandas&lt;/strong&gt; from virtually any file format, and &lt;strong&gt;sorting and displaying&lt;/strong&gt; that data in ways that let you understand it quickly.&lt;/p&gt;
&lt;p&gt;Let's get started &lt;/p&gt;
&lt;hr&gt;
&lt;h2 id=&quot;part-1-reading-files-into-pandas&quot;&gt;Part 1 — Reading Files into Pandas&lt;/h2&gt;
&lt;p&gt;Before you can analyze anything, you need to load your data. Pandas makes this simple with a family of &lt;code&gt;read_*()&lt;/code&gt; functions — one for almost every file format you'll encounter in the real world.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;csv-file-most-common&quot;&gt;CSV File — Most Common&lt;/h3&gt;
&lt;p&gt;CSV (Comma-Separated Values) files are the bread and butter of data work. &lt;code&gt;read_csv()&lt;/code&gt; is almost certainly the first Pandas function you'll use in any project.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd

df = pd.read_csv(&quot;file.csv&quot;)                          # basic read
df = pd.read_csv(&quot;file.csv&quot;, header=0)                # first row as header
df = pd.read_csv(&quot;file.csv&quot;, index_col=&quot;order_id&quot;)    # set column as index
df = pd.read_csv(&quot;file.csv&quot;, nrows=100)               # read only first 100 rows
df = pd.read_csv(&quot;file.csv&quot;, skiprows=2)              # skip first 2 rows
df = pd.read_csv(&quot;file.csv&quot;, usecols=[&quot;price&quot;,&quot;quantity&quot;])  # specific columns only
df = pd.read_csv(&quot;file.csv&quot;, na_values=[&quot;NA&quot;,&quot;?&quot;])    # define missing values
df = pd.read_csv(&quot;file.csv&quot;, sep=&quot;;&quot;)                 # semicolons instead of commas
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;excel-file&quot;&gt;Excel File&lt;/h3&gt;
&lt;p&gt;Excel files are ubiquitous in business environments. &lt;code&gt;read_excel()&lt;/code&gt; handles them cleanly, and you can target specific sheets by name or position.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df = pd.read_excel(&quot;file.xlsx&quot;)                       # basic read
df = pd.read_excel(&quot;file.xlsx&quot;, sheet_name=&quot;Sheet1&quot;)  # specific sheet by name
df = pd.read_excel(&quot;file.xlsx&quot;, sheet_name=0)         # first sheet by index
df = pd.read_excel(&quot;file.xlsx&quot;, skiprows=2)           # skip first 2 rows
df = pd.read_excel(&quot;file.xlsx&quot;, usecols=&quot;A:D&quot;)        # read columns A to D
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;json-file&quot;&gt;JSON File&lt;/h3&gt;
&lt;p&gt;JSON is the standard format for web APIs. &lt;code&gt;read_json()&lt;/code&gt; can parse various JSON structures, including a flat list of records.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df = pd.read_json(&quot;file.json&quot;)                        # basic read
df = pd.read_json(&quot;file.json&quot;, orient=&quot;records&quot;)      # list of records format
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;html-file-web-scraping-made-easy&quot;&gt;HTML File — Web Scraping Made Easy&lt;/h3&gt;
&lt;p&gt;One of Pandas' more surprising capabilities: it can extract tables directly from HTML pages, including live websites. Simple web scraping with zero extra libraries.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;tables = pd.read_html(&quot;file.html&quot;)                          # returns list of all tables
df     = pd.read_html(&quot;https://website.com/table&quot;)[0]       # first table from a URL
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;sql-database&quot;&gt;SQL Database&lt;/h3&gt;
&lt;p&gt;When your data lives in a database, Pandas can query it directly. You bring a connection object and a SQL query, and it returns a DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import sqlite3

conn = sqlite3.connect(&quot;database.db&quot;)

df = pd.read_sql(&quot;SELECT * FROM table&quot;, conn)    # full SQL query
df = pd.read_sql_table(&quot;table_name&quot;, conn)       # read entire table directly
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;text-file&quot;&gt;Text File&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;read_table()&lt;/code&gt; is the text-file counterpart to &lt;code&gt;read_csv()&lt;/code&gt;. The only real difference is its default separator — a tab instead of a comma — but it accepts all the same parameters.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df = pd.read_table(&quot;file.txt&quot;)                      # tab separated (default)
df = pd.read_table(&quot;file.txt&quot;, sep=&quot;,&quot;)             # comma separated
df = pd.read_table(&quot;file.txt&quot;, sep=&quot;;&quot;)             # semicolon separated
df = pd.read_table(&quot;file.txt&quot;, sep=&quot;|&quot;)             # pipe separated
df = pd.read_table(&quot;file.txt&quot;, header=None)         # file has no header row
df = pd.read_table(&quot;file.txt&quot;, names=[&quot;col1&quot;,&quot;col2&quot;])  # add column names manually
df = pd.read_table(&quot;file.txt&quot;, skiprows=2)          # skip first 2 rows
df = pd.read_table(&quot;file.txt&quot;, nrows=100)           # read only 100 rows
df = pd.read_fwf(&quot;file.txt&quot;)                        # fixed-width text file
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;read_csv()&lt;/code&gt; vs &lt;code&gt;read_table()&lt;/code&gt;&lt;/strong&gt; — The only practical difference is the default separator: &lt;code&gt;read_csv()&lt;/code&gt; uses a comma (&lt;code&gt;,&lt;/code&gt;) while &lt;code&gt;read_table()&lt;/code&gt; uses a tab (&lt;code&gt;\t&lt;/code&gt;). Every other parameter works identically in both.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;&lt;code&gt;read_csv()&lt;/code&gt; &lt;/th&gt;&lt;th&gt;&lt;code&gt;read_table()&lt;/code&gt;&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;Default separator &lt;/td&gt;&lt;td&gt;&lt;code&gt;,&lt;/code&gt; comma &lt;/td&gt;&lt;td&gt;&lt;code&gt;\t&lt;/code&gt; tab&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;File type &lt;/td&gt;&lt;td&gt;CSV files &lt;/td&gt;&lt;td&gt;TXT files&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Speed &lt;/td&gt;&lt;td&gt;Same &lt;/td&gt;&lt;td&gt;Same&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Parameters &lt;/td&gt;&lt;td&gt;Same &lt;/td&gt;&lt;td&gt;Same&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h3 id=&quot;other-formats&quot;&gt;Other Formats&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Clipboard — copy any table, then run this
df = pd.read_clipboard()

# Parquet — the preferred format for big data (very fast)
df = pd.read_parquet(&quot;file.parquet&quot;)

# XML
df = pd.read_xml(&quot;file.xml&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;summary-all-read-functions-at-a-glance&quot;&gt;Summary — All Read Functions at a Glance&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Function &lt;/th&gt;&lt;th&gt;File Type &lt;/th&gt;&lt;th&gt;Common Use&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_csv()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;CSV &lt;/td&gt;&lt;td&gt;Most common — daily use&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_excel()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;XLSX &lt;/td&gt;&lt;td&gt;Excel files from business&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_json()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;JSON &lt;/td&gt;&lt;td&gt;Web APIs and REST data&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_html()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;HTML &lt;/td&gt;&lt;td&gt;Web scraping tables&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_sql()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Database &lt;/td&gt;&lt;td&gt;SQL queries&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_table()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;TXT &lt;/td&gt;&lt;td&gt;Tab-separated text files&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_clipboard()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Clipboard &lt;/td&gt;&lt;td&gt;Quick copy-paste workflow&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_parquet()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Parquet &lt;/td&gt;&lt;td&gt;Large-scale / big data&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;read_xml()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;XML &lt;/td&gt;&lt;td&gt;Structured XML data&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;hr&gt;
&lt;h3 id=&quot;most-important-parameters-work-with-all-functions&quot;&gt;Most Important Parameters — Work With ALL Functions&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;nrows      →  how many rows to read
skiprows   →  how many rows to skip at the top
usecols    →  which columns to read
index_col  →  which column to use as index
na_values  →  what to treat as missing value (NaN)
header     →  which row to use as column header
sep        →  what separator/delimiter to use
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h2 id=&quot;part-2-sorting-and-displaying-data&quot;&gt;Part 2 — Sorting and Displaying Data&lt;/h2&gt;
&lt;p&gt;Once your data is loaded, the first thing you want to do is &lt;em&gt;understand&lt;/em&gt; it. The functions in this section are your primary tools for exploring structure, distributions, relationships, and ordering — before you write a single line of analysis.&lt;/p&gt;
&lt;p&gt;We'll use this sample DataFrame throughout all the examples:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import pandas as pd

data = {
    'Country':          ['China', 'India', 'USA', 'Brazil', 'UK'],
    'Continent':        ['Asia', 'Asia', 'North America', 'South America', 'Europe'],
    '2022 Population':  [1412000000, 1380000000, 331000000, 214000000, 67000000],
    'Area (km2)':       [9597000, 3287000, 9834000, 8516000, 243000]
}
df = pd.DataFrame(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;sorting-functions&quot;&gt;Sorting Functions&lt;/h3&gt;
&lt;h4 id=&quot;1-sort-values-&quot;&gt;1. sort_values()&lt;/h4&gt;
&lt;p&gt;The most commonly used sorting function. Reorders the DataFrame by the values in one or more columns. By default it sorts ascending; pass &lt;code&gt;ascending=False&lt;/code&gt; to flip it.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Ascending order (default)
df.sort_values('2022 Population')

# Descending order
df.sort_values('2022 Population', ascending=False)

# Sort by multiple columns: Continent A→Z, then Population largest first
df.sort_values(['Continent', '2022 Population'], ascending=[True, False])
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;2-sort-index-&quot;&gt;2. sort_index()&lt;/h4&gt;
&lt;p&gt;Sorts by the DataFrame's index rather than column values. This becomes important after filtering, merging, or shuffling rows, which can leave the index disordered.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.sort_index()                # sort index ascending
df.sort_index(ascending=False) # sort index descending
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;3-nlargest-&quot;&gt;3. nlargest()&lt;/h4&gt;
&lt;p&gt;Returns the top N rows with the largest values in a specified column. More efficient and more readable than combining &lt;code&gt;sort_values()&lt;/code&gt; with &lt;code&gt;head()&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Top 3 most populated countries
df.nlargest(3, '2022 Population')
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;4-nsmallest-&quot;&gt;4. nsmallest()&lt;/h4&gt;
&lt;p&gt;Returns the top N rows with the smallest values in a specified column.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# 3 smallest countries by area
df.nsmallest(3, 'Area (km2)')
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;5-rank-&quot;&gt;5. rank()&lt;/h4&gt;
&lt;p&gt;Assigns a rank to each row based on a column's values, without changing the row order. Useful for adding a ranking column to your existing DataFrame.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Add a population rank column (1 = largest)
df['Population Rank'] = df['2022 Population'].rank(ascending=False)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;displaying-functions&quot;&gt;Displaying Functions&lt;/h3&gt;
&lt;h4 id=&quot;1-head-amp-tail-&quot;&gt;1. head() &amp;amp; tail()&lt;/h4&gt;
&lt;p&gt;The simplest inspection tools. &lt;code&gt;head()&lt;/code&gt; shows the first N rows (default 5) and &lt;code&gt;tail()&lt;/code&gt; shows the last N rows. These are usually the first things you run on any new dataset.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.head()    # first 5 rows
df.head(10)  # first 10 rows
df.tail()    # last 5 rows
df.tail(3)   # last 3 rows
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;2-sample-&quot;&gt;2. sample()&lt;/h4&gt;
&lt;p&gt;Returns N randomly selected rows. Ideal for getting a representative look at a large dataset where the first or last rows might not be representative.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.sample(3)  # 3 random rows
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;3-info-&quot;&gt;3. info()&lt;/h4&gt;
&lt;p&gt;Displays the DataFrame's structure: column names, data types, number of non-null values, and memory usage. This should be one of the very first functions you call on any new dataset — it immediately reveals missing data and wrong data types.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.info()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;4-describe-&quot;&gt;4. describe()&lt;/h4&gt;
&lt;p&gt;Returns a statistical summary for all numeric columns: count, mean, standard deviation, min, max, and quartiles. A quick way to understand the scale and distribution of your data.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.describe()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;5-value-counts-&quot;&gt;5. value_counts()&lt;/h4&gt;
&lt;p&gt;Returns the frequency of each unique value in a column. Invaluable for understanding the distribution of categorical data at a glance.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# How many countries exist per continent?
df['Continent'].value_counts()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;6-corr-&quot;&gt;6. corr()&lt;/h4&gt;
&lt;p&gt;Calculates the correlation between all numeric columns. Returns values from &lt;strong&gt;-1.0&lt;/strong&gt; (perfect negative relationship) to &lt;strong&gt;1.0&lt;/strong&gt; (perfect positive relationship), with &lt;strong&gt;0.0&lt;/strong&gt; meaning no relationship.&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; &lt;code&gt;corr()&lt;/code&gt; requires numeric columns only. Always use &lt;code&gt;select_dtypes()&lt;/code&gt; before calling it to avoid a &lt;code&gt;ValueError&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Safe pattern — works on any DataFrame
df.select_dtypes(include='number').corr()

# Or select specific columns manually
df[['2022 Population', 'Area (km2)']].corr()
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;7-select-dtypes-&quot;&gt;7. select_dtypes()&lt;/h4&gt;
&lt;p&gt;Filters and returns only the columns that match a specified data type. Useful when you need to work on a subset of columns without knowing their names in advance.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.select_dtypes(include='number')              # numeric columns only (int and float)
df.select_dtypes(include='object')              # string columns only
df.select_dtypes(include='bool')                # boolean columns only
df.select_dtypes(include=['int64', 'float64'])  # specific numeric types
df.select_dtypes(exclude='object')              # drop all string columns
df.select_dtypes(exclude='number')              # drop all numeric columns
df.select_dtypes(include='number', exclude='bool')  # numeric but not boolean
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h4 id=&quot;8-select-specific-columns&quot;&gt;8. Select Specific Columns&lt;/h4&gt;
&lt;p&gt;Returns a new DataFrame containing only the columns you need. Helps reduce output to what is relevant.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df[['Country', '2022 Population']]
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;matplotlib-global-settings-plt-rcparams&quot;&gt;Matplotlib Global Settings — plt.rcParams&lt;/h3&gt;
&lt;p&gt;While not a Pandas function, &lt;code&gt;plt.rcParams&lt;/code&gt; is something you'll configure right alongside your Pandas setup. It controls the default appearance of all plots in your session — set it once at the top of your notebook and every chart inherits those settings automatically.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (20, 8)   # 20 wide, 8 tall (in inches)
plt.rcParams['font.size']       = 14       # default font size for all text
plt.rcParams['figure.dpi']      = 100      # resolution (higher = sharper)
plt.rcParams['lines.linewidth'] = 2        # default line width
plt.rcParams['axes.grid']       = True     # show grid on all plots by default
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;common-patterns&quot;&gt;Common Patterns&lt;/h3&gt;
&lt;h4 id=&quot;filter-then-sort&quot;&gt;Filter, then Sort&lt;/h4&gt;
&lt;p&gt;The most frequent real-world pattern: narrow the dataset to a subset, then rank within that subset.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Top 3 Asian countries by population
df[df['Continent'] == 'Asia'].nlargest(3, '2022 Population')
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;sort-and-preview&quot;&gt;Sort and Preview&lt;/h4&gt;
&lt;p&gt;Both lines produce the same result — the second is preferred for its clarity.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;df.sort_values('2022 Population', ascending=False).head(10)
df.nlargest(10, '2022 Population')  # ✅ preferred
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;clean-display-of-numbers&quot;&gt;Clean Display of Numbers&lt;/h4&gt;
&lt;p&gt;Control how many decimal places are shown across the entire session.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;pd.set_option('display.float_format', '{:.2f}'.format)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h3 id=&quot;complete-summary-table&quot;&gt;Complete Summary Table&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th&gt;Function &lt;/th&gt;&lt;th&gt;Category &lt;/th&gt;&lt;th&gt;Purpose&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;sort_values()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Sorting &lt;/td&gt;&lt;td&gt;Sort by column values&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;sort_index()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Sorting &lt;/td&gt;&lt;td&gt;Sort by index&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;nlargest()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Sorting &lt;/td&gt;&lt;td&gt;Get top N largest values&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;nsmallest()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Sorting &lt;/td&gt;&lt;td&gt;Get top N smallest values&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;rank()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Sorting &lt;/td&gt;&lt;td&gt;Assign rank to each row&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;head()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Show first N rows&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;tail()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Show last N rows&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;sample()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Show random N rows&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;info()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Show structure and data types&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;describe()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Statistical summary&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;value_counts()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Count frequency of unique values&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;corr()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Correlation between numeric columns&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;select_dtypes()&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Displaying &lt;/td&gt;&lt;td&gt;Filter columns by data type&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;code&gt;plt.rcParams&lt;/code&gt; &lt;/td&gt;&lt;td&gt;Matplotlib &lt;/td&gt;&lt;td&gt;Set global defaults for all plots&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;This is &lt;strong&gt;Part 1&lt;/strong&gt; of the Pandas for Data Science series. Next up: &lt;strong&gt;Part 2&lt;/strong&gt;—Filtering, Selecting &amp;amp; Cleaning Data.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;strong&gt;Refrences&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;GitHub Repo : &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/Hu8MA/Mastering-Pandas-Reference&quot;&gt;https://github.com/Hu8MA/Mastering-Pandas-Reference&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Website : &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/ &quot;&gt;https://pandas.pydata.org/ &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GitHub Library : &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/pandas-dev/pandas&quot;&gt;https://github.com/pandas-dev/pandas&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Course : &lt;a rel=&quot;nofollow&quot; href=&quot;https://youtu.be/Mdq1WWSdUtw&quot;&gt;https://youtu.be/Mdq1WWSdUtw&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/12225/mastering-pandas-part-1-reading-sorting-displaying-data</guid>
<pubDate>Thu, 26 Feb 2026 22:28:41 +0000</pubDate>
</item>
<item>
<title>Understanding the &quot;TypeError: cannot convert the series to &lt;class 'float'&gt;&quot; in Pandas</title>
<link>https://coderlegion.com/9694/understanding-the-typeerror-cannot-convert-the-series-to-class-float-in-pandas</link>
<description>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;In Python, Pandas is a powerful and effective tool for data analysis and manipulation. It performs exceptionally well with data types and structures. However, as users, when you start working with the problems of real-world datasets, you may encounter many errors. One such error that often occurs is &lt;strong&gt;&lt;code&gt;&quot;TypeError: cannot convert the series to &amp;lt;class 'float'&amp;gt;.&quot;&lt;/code&gt;&lt;/strong&gt; Generally, this error in Pandas occurs when we try to perform operations that expect numeric values on a Pandas series. In this article, we will dive deep into the causes behind this error, understand various scenarios where we can commonly find this error, and provide various debugging solutions to troubleshoot and resolve the issue.&lt;/p&gt;
&lt;h2&gt;Understanding the Error&lt;/h2&gt;
&lt;p&gt;The &lt;strong&gt;&lt;code&gt;&quot;TypeError: cannot convert the series to &amp;lt;class 'float'&amp;gt;&quot;&lt;/code&gt;&lt;/strong&gt; is a Pandas error that occurs when we try to perform operations that expect numeric values on a Pandas series. The error is an indication that the data type of the series is interrupting its conversion to a float, preventing the expected operation from being executed successfully.Let's imagine you're using Pandas to analyze customer data. You have a Series of customer ages, however some entries may be missing or contain information such as &quot;unknown&quot;. When attempting to compute average customer age, Pandas will return this error because it is unable to translate &quot;unknown&quot; to a number. Before computing the average, you must first clean the data by deleting &quot;unknown&quot; items or replacing them with a numerical value (e.g., -1).&lt;br&gt;
&lt;/p&gt;&lt;h3&gt; Common Scenarios causing this error&lt;/h3&gt;&lt;br&gt;
&lt;strong&gt;Mixing Data Types :&lt;/strong&gt;&lt;br&gt;
Consider the following example:
&lt;pre&gt;&lt;code&gt;import pandas as pd

# creating df which is a data frame with mixed data types
data = {'column1': [1, 'two', 3, 4.5]}
df = pd.DataFrame(data)

# Attempting to perform a numeric operation on the mixed data
result = float(df['column1'])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, the presence of a string ('two') in the 'column1' series hinders the conversion to a float which eventually leads to &quot;TypeError: cannot convert the series to &quot;. The output of this looks as follows:&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12048529278459622337&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Null or Missing Values :&lt;/strong&gt;&lt;br&gt;
Now, let's explore another example involving missing values:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# creating df which is a data frame with a missing value
data = {'column1': [1, 2, None, 4.5]}
df = pd.DataFrame(data)

# Attempting to perform a numeric operation on a Series with missing values
result = float(df['column1'])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example, the presence of a None in the 'column1' series hinders the conversion to a float, which eventually leads to &quot;TypeError: cannot convert the series to &quot;. The output of this looks as follows:&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16286088693492546867&quot; alt=&quot;&quot;&gt;&lt;br&gt;
&lt;/p&gt;&lt;h2&gt; Solutions to the &quot;TypeError&quot; &lt;/h2&gt;&lt;br&gt;
The first step in fixing the &lt;strong&gt;&quot;TypeError&quot;&lt;/strong&gt; is figuring out the cause of the error. Here are two common situations where it occurs and their respective solutions:
&lt;h3&gt; Handling Mixed Data Types&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Convert the 'column1' Series to numeric, coercing errors to NaN
df['column1'] = pd.to_numeric(df['column1'], errors='coerce')

# Now perform the numeric operation
result = df['column1'].apply(float)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this solution, the 'column1' series is converted to a numeric format using the &lt;strong&gt;pd.to_numeric()&lt;/strong&gt; function. The substitution of NaN for non-convertible values is ensured by the &lt;em&gt;errors='coerce'&lt;/em&gt; parameter. The numeric operation can be carried out without causing a &lt;strong&gt;&quot;TypeError&quot;&lt;/strong&gt; once the conversion is finished.&lt;/p&gt;
&lt;h3&gt; Handling Missing Values &lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Filling missing values with a default value (e.g., 0)
df['column1'].fillna(0, inplace=True)

# Now perform the numeric operation
result = df['column1'].apply(float)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this solution, the &lt;strong&gt;fillna()&lt;/strong&gt; function is used to fill in the missing values in the 'column1' series with a default value, such as 0. This guarantees that every value in the series is a number, enabling the numeric operation to be carried out successfully.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt; Exploring Best Practices &lt;/h2&gt;&lt;br&gt;
In addition to fixing the current issue, using best practices when working with Pandas dataframes will help reduce the possibility of similar errors occurring in the future.
&lt;h3&gt; Data Type Consistency &lt;/h3&gt;
&lt;p&gt;A dataframe's ability to function properly depends on the data types inside it being consistent. &lt;strong&gt;Make sure the series only has numerical values in it before beginning any numerical actions&lt;/strong&gt;. To determine a series' data type, utilize the dtype attribute.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Checking the datatype of the 'column1' Series
print(df['column1'].dtype)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To standardise the data type, if it is not what you expected, think about using conversion functions like &lt;strong&gt;&lt;em&gt;pd.to_numeric().&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt; Error Handling &lt;/h3&gt;
&lt;p&gt;Adopting strong error-handling procedures becomes essential in situations where data quality fluctuates. The graceful handling of non-convertible values is made possible by the use of functions like &lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html&quot;&gt;pd.to_numeric()&lt;/a&gt;&lt;/strong&gt; with error handling options like &lt;strong&gt;errors='coerce,'&lt;/strong&gt; which prevent errors from stopping the process altogether.&lt;/p&gt;
&lt;h3&gt;Missing Value Strategies&lt;/h3&gt;
&lt;p&gt;In data analysis, handling missing values is a frequent problem. To make sure the data frame is still appropriate for numeric operations, use an appropriate approach, such as using &lt;strong&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html&quot;&gt;fillna()&lt;/a&gt;&lt;/strong&gt; to fill in missing values with a default or calculated value.&lt;/p&gt;
&lt;h3&gt; Data Cleaning and Preprocessing &lt;/h3&gt;
&lt;p&gt;Take the time to thoroughly clean and preprocess your data before executing any complicated operations. The chance of running into errors later on can be greatly decreased by spotting and &lt;strong&gt;fixing outliers, inconsistent data, and missing values early in the process&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt; Conclusion &lt;/h2&gt;
&lt;p&gt;Finally, the Pandas &lt;strong&gt;&lt;code&gt;&quot;TypeError: cannot convert the series to&amp;lt;class 'float'&amp;gt;&quot;&lt;/code&gt;&lt;/strong&gt; message is a useful reminder of how critical it is to preserve consistent, high-quality data in the field of data science. For data manipulation processes to be error-free, it is essential to comprehend the root causes of these errors and put workable fixes in place. Users can strengthen their data analysis workflows and derive valuable insights from a variety of datasets by &lt;strong&gt;implementing strong error handling, encouraging data type consistency, and developing strategies for handling missing values&lt;/strong&gt;. Python is still the most popular language for data science and analysis, which emphasises how important it is to understand the subtleties of error correction and follow best practices in order to successfully negotiate the complexities of data manipulation. Gaining expertise in error correction and best practices implementation is not only a necessary skill in this ever-changing environment, but also a vital means of gaining access to insightful knowledge from the wide and diverse world of datasets.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt; References &lt;/h2&gt;&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12048529278459622337&quot;&gt;1&lt;/a&gt; pandas.to_numeric — pandas documentation. (n.d.). Retrieved from &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html&quot;&gt;https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html&lt;/a&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9694/understanding-the-typeerror-cannot-convert-the-series-to-class-float-in-pandas</guid>
<pubDate>Wed, 14 Jan 2026 11:58:14 +0000</pubDate>
</item>
<item>
<title>Which method can be used to add a group of elements to a set?</title>
<link>https://coderlegion.com/9693/which-method-can-be-used-to-add-a-group-of-elements-to-a-set</link>
<description>&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Adding a group of elements to a set in &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.python.org/doc/&quot;&gt;Python&lt;/a&gt; is a common task encountered in programming when dealing with collections of unique elements. This problem arises when there's a need to incorporate multiple items into an existing set efficiently. Sets in Python ensure uniqueness, meaning duplicate elements are automatically filtered out. However, adding a group of elements to a set requires special attention to maintain this uniqueness while achieving the desired functionality. Fortunately, Python offers various methods to address this challenge, providing flexibility and efficiency in managing sets. By understanding these methods, programmers can effectively manipulate sets to accommodate new elements while preserving their distinctiveness.&lt;/p&gt;
&lt;h3 id=&quot;what-is-a-set-&quot;&gt;What is a Set?&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;In Python, sets are a fundamental data structure used for &lt;strong&gt;storing collections of unique elements&lt;/strong&gt;. Unlike lists or tuples, sets do not allow duplicate values, ensuring that each element within the set is unique. Sets are unordered, meaning that the elements are not stored in any particular order, and they are mutable, allowing for dynamic changes to the set's contents.&lt;/li&gt;
&lt;li&gt;Sets in Python are like containers that holds a collection of unique items.&lt;/li&gt;
&lt;li&gt;Imagine you have an empty bag where you can only keep unique items; that's essentially what a set is.&lt;/li&gt;
&lt;li&gt;Each item in a set is distinct, and the order doesn't matter. If you try to put a duplicate item, it simply won't go in.&lt;/li&gt;
&lt;li&gt;Sets in Python are denoted by curly braces &lt;code&gt;{}&lt;/code&gt; enclosing a comma-separated list of elements, or by using the &lt;code&gt;set()&lt;/code&gt; constructor. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let's look at a small example to understand what a set is,&lt;/p&gt;
&lt;h3 id=&quot;example&quot;&gt;EXAMPLE&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  # Unique Elements
     fruits_1 = {'mango', 'apple', 'orange', 'kiwi'}
     print(&quot;Set of Fruits-1 : &quot;, fruits_1)

     # Even if I repeat elements, it will consider that element to be unique only
     fruits_2 = {'mango', 'apple', 'orange', 'kiwi','orange'}
     print(&quot;Set of Fruits-2: &quot;, fruits_2)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1266818688928413254&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;adding-a-group-of-elements-to-a-set&quot;&gt;Adding a group of elements to a set&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Using &lt;code&gt;update()&lt;/code&gt; method&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;|&lt;/code&gt; Operator&lt;/li&gt;
&lt;li&gt;Using Set Union Method - &lt;code&gt;union()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Using Set Comprehension&lt;/li&gt;
&lt;li&gt;Using Set Constructor&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These methods offer flexibility in adding a single element or a group of elements to a set in Python-3.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt; &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Define a set
my_set = {1, 2, 3}

# Define a list of elements to add
to_add_elements = [4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;method---1&quot;&gt;Method - 1&lt;/h2&gt;
&lt;h3 id=&quot;using-update-method&quot;&gt;Using &lt;code&gt;'update()'&lt;/code&gt; method&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;This method directly adds multiple elements to a set in Python-3.&lt;/li&gt;
&lt;li&gt;It takes an iterable (such as a list, tuple, or set) as input and modifies the set by adding all elements from the iterable.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set.update(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 1: Using update() method
my_set.update(to_add_elements)
print(&quot;my_set&quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Use `update()` method when you want to directly add multiple elements to a set.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;method---2&quot;&gt;Method - 2&lt;/h2&gt;
&lt;h3 id=&quot;using-operator&quot;&gt;Using &lt;code&gt;'|'&lt;/code&gt; Operator&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The set union operator (|) performs a union operation between two sets, adding elements from both sets to create a new set.&lt;/li&gt;
&lt;li&gt;It combines the existing set with another set created from an iterable using the set() constructor.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set |= set(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 2: Using '|' operator
my_set |= set(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;method---3&quot;&gt;Method - 3&lt;/h2&gt;
&lt;h3 id=&quot;using-set-union-method---union-&quot;&gt;Using Set Union Method - &lt;code&gt;'union()'&lt;/code&gt;&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The union() method returns a new set containing all the elements from the existing set and an iterable.&lt;/li&gt;
&lt;li&gt;It doesn't modify the original set but creates a new set with the&lt;br&gt;
 combined elements.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = my_set.union(elements_to_add)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 3: Using union() method
my_set = my_set.union(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;method---4&quot;&gt;Method - 4&lt;/h2&gt;
&lt;h3 id=&quot;using-set-comprehension&quot;&gt;Using Set Comprehension&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Set comprehension is a concise way to create sets in Python by iterating over an iterable.&lt;/li&gt;
&lt;li&gt;It allows for adding elements from the iterable to the set while creating it.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = {element for element in my_set} | set(elements_to_add)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 4: Using set comprehension
my_set = {element for element in my_set} | set(to_add_elements)
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Employ set comprehension for a concise way to create sets by iterating over an iterable.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;method---5&quot;&gt;Method - 5&lt;/h2&gt;
&lt;h3 id=&quot;using-set-constructor&quot;&gt;Using Set Constructor&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The set() constructor creates a new set from an iterable, automatically removing any duplicate elements.&lt;/li&gt;
&lt;li&gt;It can be combined with set operations like union to add elements from the iterable to the existing set.&lt;/li&gt;
&lt;li&gt;Example: &lt;code&gt;my_set = my_set.union(set(elements_to_add))&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Method 5: Using set constructor
my_set = my_set.union(set(to_add_elements))
print(&quot;my_set : &quot;, my_set)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13440198384683147114&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;all-the-5-methods-in-one-go-&quot;&gt;All the 5 Methods in One Go!&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Define a set
my_set = {1, 2, 3}

# Define a list of elements to add
elements_to_add = [4, 5, 6]

# Method 1: Using update() method
my_set.update(elements_to_add)

# Method 2: Using set union (| operator)
my_set |= set(elements_to_add)

# Method 3: Using union() method
my_set = my_set.union(elements_to_add)

# Method 4: Using set comprehension
my_set = {element for element in my_set} | set(elements_to_add)

# Method 5: Using set constructor
my_set = my_set.union(set(elements_to_add))
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Pay attention to the performance implications of each method, especially when dealing with large sets.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;best-practices&quot;&gt;Best Practices&lt;/h2&gt;
&lt;p&gt;Here are some best practices to follow when adding elements to a set:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Choose the most appropriate method:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Depending on your specific use case and preference, choose the method that best suits your needs. Each method has its advantages, but some might be more efficient or readable depending on the context.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Use update() for simplicity:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;When you want to add multiple elements to an existing set and modify it in place, update() is the simplest and most straightforward method. It directly modifies the original set without creating a new one.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Document your code:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Clearly document your code, especially if you're using less common methods or if the purpose of the code might not be immediately obvious. Documenting your code helps other developers understand your intentions and use your code effectively.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;h3&gt;&lt;strong&gt;Test thoroughly:&lt;/strong&gt;&lt;/h3&gt;
    &lt;p&gt;Test your code with various inputs and edge cases to ensure it behaves as expected. Consider writing unit tests to automate testing and catch regressions.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Ensure that the elements you're adding to the set are unique to maintain set's uniqueness property.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Be cautious when using set comprehension with large iterables, as it may lead to increased memory usage.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Sets in Python are collections of unique elements, akin to a bag where each item is distinct.&lt;/li&gt;
&lt;li&gt;They are useful for tasks requiring uniqueness, like removing duplicates or finding unique elements.&lt;/li&gt;
&lt;li&gt;Various methods exist to add a group of elements to a set, including update(), set union (| operator), union() method, set comprehension, and set constructor.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In simpler terms, when working with sets in Python, you have different methods for adding multiple items. You can choose the one that suits your needs best:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If you want a straightforward approach, you can use update().&lt;/li&gt;
&lt;li&gt;For a more elegant solution, you can use | (the pipe symbol).&lt;/li&gt;
&lt;li&gt;If you need more flexibility, union() is a good option.&lt;/li&gt;
&lt;li&gt;If you prefer concise code, you can use set comprehension.&lt;/li&gt;
&lt;li&gt;And if you need to build a set from other iterable types, you can use the set constructor.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Understanding these methods helps you manage sets effectively, ensuring that each item you add remains unique.&lt;/p&gt;
&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Python documentation:&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.python.org/doc/&quot;&gt;https://www.python.org/doc/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/9693/which-method-can-be-used-to-add-a-group-of-elements-to-a-set</guid>
<pubDate>Wed, 14 Jan 2026 11:54:37 +0000</pubDate>
</item>
<item>
<title>&quot;Only valid with datetimeindex, timedeltaindex or periodindex, instance of 'index'&quot; Solved</title>
<link>https://coderlegion.com/7689/only-valid-with-datetimeindex-timedeltaindex-or-periodindex-instance-of-index-solved</link>
<description>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;In Python, Pandas is a powerful and effective tool for data analysis and manipulation. It performs exceptionally well with data types and structures. However, when it comes to time-series data, users occasionally encounter the following errors: &lt;strong&gt;&quot;Only valid with DatetimeIndex, TimedeltaIndex, or PeriodIndex, but got an instance of 'index'&quot;&lt;/strong&gt;. The error message usually appears when attempting time-related operations on a DataFrame or Series that does not have a proper time-based index. To resolve this error, users should use &lt;strong&gt;&lt;em&gt;pd.to_datetime() to convert the existing index to a DatetimeIndex&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;set a datetime column as the index with set_index()&lt;/em&gt;&lt;/strong&gt;. In this article, we will try to explore and understand the significance of using these time-based indexes in Pandas and take a look into solutions for addressing this common issue.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt;Understanding The Types of Index in Pandas &lt;/h2&gt;&lt;br&gt;
In Pandas, there are various types of index errors, such as &lt;strong&gt;Int64Index, RangeIndex, and DatetimeIndex, among others&lt;/strong&gt;. An index is important for effective data manipulation and retrieval. Using a time-based index for time-series data enhances the performance of temporal operations seamlessly.&lt;br&gt;
A &lt;strong&gt;DatetimeIndex&lt;/strong&gt; is the best option for time-series data analysis. It uses timestamps as the index to provide sophisticated time-based operations. You can easily calculate time differences, resample data to different frequencies, and filter by date ranges. This systematic technique dramatically increases your performance while working with temporal data.
&lt;h2&gt; Significance of Time-based Indexing &lt;/h2&gt;
&lt;p&gt;Understanding change relies heavily on time-series data. It's a set of measurements taken like snapshots at precise times, allowing us to see how things change over time. Stock prices ticking every minute, or daily temperature readings taken over a year, are typical examples. The key, however, is in the time-based index, an invisible timeline that assures each data piece is in the correct location.&lt;br&gt;
This time index is the key to accessing powerful analytical tools. &lt;strong&gt;Want to compare average monthly sales data over the last year?&lt;/strong&gt; Using a time index makes this simple. You may easily segment the data by month, generate monthly averages, and identify trends. &lt;strong&gt;Need to see the broad picture?&lt;/strong&gt; You can aggregate data into larger periods, such as quarters. &lt;strong&gt;Are you analyzing at a different pace?&lt;/strong&gt;. Resample the data from hourly to daily. However, without a time index, these procedures become error-prone. The system simply cannot grasp the order of your data points, resulting in annoying error messages. Remember that a time-based index is the cornerstone for unlocking the true potential of your time series data exploration.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt;Common Mistakes: 'Only valid with DatetimeIndex, TimedeltaIndex, or PeriodIndex'&lt;/h2&gt;&lt;br&gt;
Ever get annoyed when you try to examine data over time and just get error messages? It's as if the computer does not grasp what you're asking for. The root cause is a missing time-based index. This index functions as a calendar for your data, ensuring that each point is properly arranged.
&lt;p&gt;The issue often appears when you do time-sensitive operations on data that does not include this calendar. This can occur when you &lt;strong&gt;import data without providing the time component&lt;/strong&gt;, or &lt;strong&gt;when the data lacks temporal information&lt;/strong&gt;. It's like attempting to examine a movie with every scene jumbled together; you can't follow the tale! So, a time-based index is critical for making sense of your data and identifying trends across time.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt;Debugging the Issue: Converting to Time-based Index &lt;/h2&gt;&lt;br&gt;
To debug the error, You are required to convert the existing index to a time-based index. There are several methods for that purpose, which are:&lt;br&gt;
&lt;h3&gt;Using pd.to_datetime()&lt;/h3&gt;&lt;br&gt;
The &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html&quot;&gt;pd.to_datetime()&lt;/a&gt; function is a flexible tool used for &lt;strong&gt;converting various date-like objects to Pandas datetime objects&lt;/strong&gt;. You can transform your existing dataframe into a DatetimeIndex by implementing this function.
&lt;pre&gt;&lt;code&gt;import pandas as pd

# df is a data frame with a generic index
df.index = pd.to_datetime(df.index)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Creating a DatetimeIndex &lt;/h3&gt;
&lt;p&gt;You can &lt;strong&gt;create a new DatetimeIndex based&lt;/strong&gt; on that column with time-related information in your dataset.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
# Here, 'time_column' is containing time related information such as date
df['time_column'] = pd.to_datetime(df['time_column'])
df.set_index('time_column', inplace=True)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Generating a TimedeltaIndex &lt;/h3&gt;
&lt;p&gt;You can &lt;strong&gt;convert your index to TimedeltaIndex&lt;/strong&gt; if the index represents the duration.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
# here df is a data frame with index representing durations
df.index = pd.to_timedelta(df.index)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Utilising PeriodIndex&lt;/h3&gt;
&lt;p&gt;You can &lt;strong&gt;create a PeriodIndex&lt;/strong&gt; when you are dealing with data that is relevant for a specific period (e.g., monthly or quarterly).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# here df is data frame with an index representing periods with freq='M' seting it frequency to monthly.
df.index = pd.PeriodIndex(df.index, freq='M') 
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt; Understand the Debugging Process with a real-world example &lt;/h2&gt;
&lt;p&gt;Let's now understand the debugging process with a practical example. Suppose you have a data frame with a non time-based index and humidity readings.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
import numpy as np

# Creating a sample data frame
data = {'Humidity': np.random.rand(5)}
df = pd.DataFrame(data)

# Trying a time-based operation without a suitable index
try:
 df['Date'] = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05']
 df.index = df['Date']
 daily_mean = df.resample('D').mean()
except ValueError as e:
 print(f&quot;Error: {e}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5661725463133185879&quot; alt=&quot;&quot;&gt;&lt;br&gt;
In the above example, we tried to assign a date column to the index, which is recognised as a string by Pandas. If you try any datetime operation on the index that results in errors, which require a proper time-based index to debug.&lt;br&gt;
Now, let's convert the &lt;strong&gt;index to a DatetimeIndex&lt;/strong&gt; for debugging.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Convert the index to DatetimeIndex
df.index = pd.to_datetime(df.index)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This above change will allow you to use time-based operations on the DataFrame seamlessly.&lt;/p&gt;
&lt;h2&gt; Conclusion &lt;/h2&gt;
&lt;p&gt;In summary  Pandas time series data handling requires the use of time-based indexes. They guarantee that your data is accurately arranged and give you the ability to carry out effective time-based analysis. It's a good idea to confirm that your data has the correct time index before beginning any time series analysis, as indicated by the error notice &lt;strong&gt;Only valid with &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.html&quot;&gt;DatetimeIndex&lt;/a&gt;, &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/reference/api/pandas.TimedeltaIndex.html&quot;&gt;TimedeltaIndex&lt;/a&gt;, or &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/reference/api/pandas.PeriodIndex.html&quot;&gt;PeriodIndex&lt;/a&gt;&lt;/strong&gt;&quot;.&lt;/p&gt;
&lt;p&gt;Fortunately, Pandas has ways to change your data into a temporally organized format, such as using &lt;strong&gt;pd.to_datetime(), DatetimeIndex, TimedeltaIndex, or PeriodIndex&lt;/strong&gt;. By using these techniques, you may avoid mistakes and fully utilize Pandas' time series capabilities, which will enable you to gain insightful knowledge from your data.&lt;br&gt;
&lt;/p&gt;&lt;h2&gt; References &lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Pandas Documentation: &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/&quot;&gt;https://pandas.pydata.org/docs/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;Python Documentation ( Datetime module ):&lt;br&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/library/datetime.html&quot;&gt;https://docs.python.org/3/library/datetime.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/7689/only-valid-with-datetimeindex-timedeltaindex-or-periodindex-instance-of-index-solved</guid>
<pubDate>Mon, 24 Nov 2025 00:10:04 +0000</pubDate>
</item>
<item>
<title>Performance Comparison: Pandas vs. NumPy for Data Analysis</title>
<link>https://coderlegion.com/6052/performance-comparison-pandas-vs-numpy-for-data-analysis</link>
<description>&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=1883086296129124361&quot; alt=&quot;&quot;&gt;&lt;br&gt;
NumPy excels at fast, memory-efficient numerical computations on homogeneous data arrays and is significantly faster for basic operations like arithmetic, slicing, and mean calculations, especially on smaller datasets (less than 50,000 rows).&lt;/p&gt;
&lt;p&gt;Pandas provides user-friendly tools for tabular, heterogeneous data, supports complex operations (like groupby, merging, handling missing data), and allows more flexible data manipulation, but has more overhead resulting in slower performance for basic calculations compared to NumPy.&lt;/p&gt;
&lt;p&gt;For large datasets (500,000 rows or more), Pandas can outperform NumPy for certain data operations due to internal optimizations; between 50,000 and 500,000 rows, performance differences are operation-dependent.&lt;/p&gt;
&lt;p&gt;NumPy uses less memory and is optimal for machine learning model inputs, while Pandas is preferred for rich data analysis, data cleaning, and working directly with external sources like CSV or Excel files.&lt;/p&gt;
&lt;p&gt;Indexing is faster in NumPy, while Pandas offers more advanced indexing and labeling but at the cost of speed.&lt;/p&gt;
</description>
<category>Data Science</category>
<guid isPermaLink="true">https://coderlegion.com/6052/performance-comparison-pandas-vs-numpy-for-data-analysis</guid>
<pubDate>Sat, 04 Oct 2025 12:29:19 +0000</pubDate>
</item>
<item>
<title>Mastering Data Analysis and Manipulation with Pandas: A Comprehensive Guide</title>
<link>https://coderlegion.com/1755/mastering-data-analysis-and-manipulation-with-pandas-a-comprehensive-guide</link>
<description>&lt;p&gt;This article covers Pandas, an essential Python data analysis and manipulation library. &lt;strong&gt;Data handling&lt;/strong&gt; is made easier using Pandas, from pre-processing to more complex tasks like &lt;strong&gt;time series analysis&lt;/strong&gt;. It addresses the generation of pivot tables, method chaining for effective processing, and handling of both text and category data, with an emphasis on advanced techniques. Users can get more &lt;strong&gt;robust insights&lt;/strong&gt; and improve their data analysis operations by becoming proficient with these functionalities.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15220199467328289560&quot; alt=&quot;&quot; width=&quot;740&quot; height=&quot;350&quot;&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents: &lt;a id=&quot;toc-toogle&quot; class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;div id=&quot;toc-div&quot;&gt;
&lt;div id=&quot;toc-list&quot;&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#iex&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Data Cleaning and Preprocessing&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#dir&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Data Visualization with Pandas&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#num&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Time Series Analysis with Pandas&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#numpy&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Advanced Pandas Techniques&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#con&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;
&lt;section&gt;&lt;a id=&quot;iex&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Data Cleaning and Preprocessing&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;1. Handling missing data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas manages missing data in DataFrames effectively: fillna() and dropna() replace or drop missing values, respectively, and isnull() or notnull() detects them.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
data = {'A': [1, 2, None, 4],&lt;br&gt;
        'B': [None, 5, 6, 7],&lt;br&gt;
        'C': [8, 9, 10, 11]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Detecting missing values&lt;br&gt;
print(&quot;Missing Values:&quot;)&lt;br&gt;
print(df.isnull())&lt;br&gt;
# Filling missing values with 0&lt;br&gt;
filled_df = df.fillna(value=0)&lt;br&gt;
print(&quot;\nDataFrame after filling missing values:&quot;)&lt;br&gt;
print(filled_df)&lt;br&gt;
clean_df = df.dropna()&lt;br&gt;
print(&quot;\nDataFrame after dropping missing values:&quot;)&lt;br&gt;
print(clean_df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Data Type Conversion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas frequently performs data type conversion to guarantee consistency and interoperability across various data types. You can convert the data types of columns in a Data Frame using the astype() method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': ['25.5, '30.3', '22.7'],# Age as string 'Date': ['2022-01-01', '2022-02-01', '2022-03-01']} # Date as strings&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Convert 'Age' column to float&lt;br&gt;
df['Age'] = df['Age'].astype(float)&lt;br&gt;
# Convert 'Date' column to datetime&lt;br&gt;
df['Date'] = pd.to_datetime(df['Date'])&lt;br&gt;
print(df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-red&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Use caution when processing huge datasets in pieces, as this can still result in high memory usage, particularly when complicated calculations or data manipulation are involved. &lt;/span&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;3. Removing Duplicates&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;During data cleaning and pre processing, removing duplicates in Pandas Data Frame is a common procedure.  Duplicates can be removed using the &lt;code&gt;'drop_duplicates()'&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'Name': ['John', 'Anna', 'John', 'Linda', 'Anna'],&lt;br&gt;
        'Age': [28, 35,  28, 45, 35]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Remove duplicate rows&lt;br&gt;
unique_df = df.drop_duplicates()&lt;br&gt;
print(&quot;DataFrame after removing duplicate rows:&quot;)&lt;br&gt;
print(unique_df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=984319935711031604&quot; alt=&quot;&quot; width=&quot;460&quot; height=&quot;340&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Data normalization and scaling&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Preprocessing data with scaling and normalisation helps to standardise feature ranges for better machine learning. Standardisation sets features to mean 0 and standard deviation 1, whereas normalisation scales characteristics to 0-1.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
from sklearn.preprocessing import MinMaxScaler, StandardScaler&lt;br&gt;
# Sample DataFrame&lt;br&gt;
data = {'Feature1': [10, 20, 30, 40, 50],&lt;br&gt;
        'Feature2': [1, 2, 3, 4, 5]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Min-Max scaling&lt;br&gt;
min_max_scaler = MinMaxScaler()&lt;br&gt;
normalized_data = min_max_scaler.fit_transform(df[['Feature1', 'Feature2']])&lt;br&gt;
# Standardization&lt;br&gt;
standard_scaler = StandardScaler()&lt;br&gt;
standardized_data = standard_scaler.fit_transform(df[['Feature1', 'Feature2']])&lt;br&gt;
print(&quot;Normalized Data:&quot;)&lt;br&gt;
print(normalized_data)&lt;br&gt;
print(&quot;\nStandardized Data:&quot;)&lt;br&gt;
print(standardized_data)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Data Visualization with Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;With Pandas, you can quickly gain understanding of your data by creating simple plots straight from Data Frames for data visualization. Pandas uses the robust charting tool Matplotlib to facilitate visualization. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Basic plotting &lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas offers easy-to-use techniques for basic plotting, including scatter plots, histograms, bar graphs, and line plots. On a Data Frame or Series, you can directly call these graphing functions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
# Creating a DataFrame&lt;br&gt;
data = {'Date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'],&lt;br&gt;
        'Value': [10, 15, 20, 25],&lt;br&gt;
        'Category': ['A', 'B', 'C', 'D'],&lt;br&gt;
        'Count': [5, 3, 4, 2],&lt;br&gt;
        'Feature1': [1, 2, 3, 4],&lt;br&gt;
        'Feature2': [5, 6, 7, 8]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Line plot&lt;br&gt;
df.plot(x='Date', y='Value', kind='line')&lt;br&gt;
plt.title('Line Plot')&lt;br&gt;
# Bar plot&lt;br&gt;
df.plot(x='Category', y='Count', kind='bar')&lt;br&gt;
plt.title('Bar Plot')&lt;br&gt;
# Show plots&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Customizing plots&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To alter the look of plots, pandas plotting functions support a wide range of choices, such as colours, labels, titles, grid lines, and more. You can customize the visualization to meet your own requirements by adjusting these settings.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Creating a DataFrame&lt;br&gt;
data = {'Date': ['2022-01-01', '2022-01-02','2022-01-03', '2022-01-04'],&lt;br&gt;
        'Value': [10, 20, 15, 25]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Changing colors&lt;br&gt;
df.plot(color=['blue'])&lt;br&gt;
# Adding labels and title&lt;br&gt;
df.plot(x='Date', y='Value', xlabel='Date',&lt;br&gt;
        ylabel='Value', title='Value over Time')&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;strong&gt;3. Subplots and multiple axes&lt;/strong&gt;
&lt;p&gt;Pandas enables the setting up of numerous axes and subplots inside a single figure. You can compare several datasets or different features of your data by visualizing them side by side with this functionality.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Creating a DataFrame&lt;br&gt;
data = {'Date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'],&lt;br&gt;
        'Value': [10, 20, 15, 25],&lt;br&gt;
        'Count': [5, 3, 4, 2]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Convert 'Date' column to datetime format&lt;br&gt;
df['Date'] = pd.to_datetime(df['Date'])  &lt;br&gt;
# Subplots&lt;br&gt;
df.plot(subplots=True, figsize=(10, 8))&lt;br&gt;
# Multiple axes&lt;br&gt;
ax1 = df.plot(x='Date', y='Value', color='blue')&lt;br&gt;
ax2 = df.plot(x='Date', y='Count', color='red', secondary_y=True, ax=ax1)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;num&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Time Series Analysis with Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Using Pandas for time series analysis involves handling and examining data that is indexed by time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Handling time series data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas can be used to work with time series data by creating datetime objects from strings or numeric representations of dates. Date-like objects can be converted into datetime objects using the pd.to_datetime() function.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'Date': ['2024-03-13', '2024-03-14', '2024-03-15'],&lt;br&gt;
        'Value': [10, 20, 30]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Parsing dates&lt;br&gt;
df['Date'] = pd.to_datetime(df['Date'])&lt;br&gt;
# Setting datetime index&lt;br&gt;
df.set_index('Date', inplace=True)&lt;br&gt;
print(df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15254059698899200817&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;350&quot;&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Resampling and frequency conversion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The resample() function in Pandas allows you to aggregate data at multiple intervals of time, either up-sampling or down-sampling (data to a higher or lower frequency).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandasa as pd&lt;br&gt;
data = {'Date': pd.date_range(start='2024-01-01', end='2024-03-15'),&lt;br&gt;
        'Value': range(1, 76)}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Setting 'Date' column as datetime index&lt;br&gt;
df.set_index('Date', inplace=True)&lt;br&gt;
# Downsampling from daily to monthly&lt;br&gt;
monthly_data = df.resample('M').mean()&lt;br&gt;
# Upsampling from monthly to daily&lt;br&gt;
daily_data = monthly_data.resample('D').ffill()  # Forward fill missing values&lt;br&gt;
print(&quot;Monthly Data:&quot;)&lt;br&gt;
print(monthly_data.head())&lt;br&gt;
print(&quot;\nDaily Data:&quot;)&lt;br&gt;
print(daily_data.head())&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7447374094229819563&quot; alt=&quot;&quot; width=&quot;330&quot; height=&quot;290&quot;&gt;&lt;br&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; To handle data in smaller chunks, reduce memory errors, and increase efficiency for huge datasets, use chunksize when using pandas' read_csv() or read_sql() functions&lt;span class=&quot;alert-body&quot;&gt;. &lt;/span&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;3. Time shifting and lagging&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas has methods like shift() and diff() that let you shift or lag time series data. Data shifting can be helpful in calculating variations or changes over time.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'Date': pd.date_range(start='2024-01-01', end='2024-01-05'),&lt;br&gt;
        'Value': [10, 15, 20, 25, 30]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Shifting data by one period&lt;br&gt;
df['Shifted'] = df['Value'].shift(1)&lt;br&gt;
# Calculating differences between consecutive elements&lt;br&gt;
df['Diff'] = df['Value'].diff()&lt;br&gt;
print(df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3905265585194642992&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;400&quot;&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;numpy&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Advanced Pandas Techniques&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In the scope of fundamental functions, efficient and effective data manipulation and analysis are made possible by advanced Pandas approaches.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Handling categorical data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Categorical data is effectively managed by Pandas using pd. To create dummy variables, use pd.get_dummies() and categorical() for fixed distinct values.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
data = {'Category': ['A', 'B', 'C', 'A', 'B', 'C']}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Convert 'Category' column to categorical&lt;br&gt;
df['Category'] = pd.Categorical(df['Category'],categories=['A', 'B', 'C'])&lt;br&gt;
# Convert categorical variable into dummy/indicator variables&lt;br&gt;
dummy_df = pd.get_dummies(df['Category'], prefix='Category')&lt;br&gt;
print(&quot;Original DataFrame:&quot;)&lt;br&gt;
print(df)&lt;br&gt;
print(&quot;\nDummy DataFrame:&quot;)&lt;br&gt;
print(dummy_df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Working with text data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas has several string methods (such str.lower() and str.contains()) that can be used to work with text data in Data Frame columns. Advanced text processing activities can also be carried out with regular expressions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
data = {'Text': ['This is a Text with Keyword', 'Another text without the keyword']}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Convert 'Text' column to lowercase&lt;br&gt;
df['Text'] = df['Text'].str.lower()&lt;br&gt;
# Check if text contains a specific substring&lt;br&gt;
contains_substring = df['Text'].str.contains('keyword')&lt;br&gt;
# Extract text using regular expressions&lt;br&gt;
extracted_text = df['Text'].str.extract(r'(\d+)')&lt;br&gt;
print(df)&lt;br&gt;
print(contains_substring)&lt;br&gt;
print(extracted_text)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;3. Pivot tables and cross-tabulations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To aggregate and sum data based on variables, pivot tables can be created using Pandas' pivot_table() function. In a similar manner, cross-tabulations are used by pd.crosstab() to compute frequency tables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
import numpy as np&lt;br&gt;
data = {'Date': pd.date_range(start='2024-01-01', periods=6),&lt;br&gt;
        'Category': ['A', 'B', 'A', 'C', 'B', 'C'],&lt;br&gt;
        'Value': [10, 20, 15, 25, 30, 35]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Create a pivot table&lt;br&gt;
pivot_table = pd.pivot_table(df, values='Value', index='Date', columns='Category', aggfunc=np.sum)&lt;br&gt;
print(&quot;Pivot Table:&quot;)&lt;br&gt;
print(pivot_table)&lt;br&gt;
# Sample DataFrame for cross-tabulation&lt;br&gt;
data_cross_tab = {'Category1': ['A', 'B', 'A', 'C', 'B', 'C'], 'Category2': ['X', 'Y', 'X', 'Y', 'X', 'Y']}&lt;br&gt;
df_cross_tab = pd.DataFrame(data_cross_tab)&lt;br&gt;
# Create a cross-tabulation&lt;br&gt;
cross_tab = pd.crosstab(df_cross_tab['Category1'], df_cross_tab['Category2'])&lt;br&gt;
print(&quot;\nCross-Tabulation:&quot;)&lt;br&gt;
print(cross_tab)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;4. Method chaining&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Code readability and workflow efficiency are increased by the Pandas method chaining, which reduces several processes into a single line.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
data = {'Category': ['A', 'B', 'A', 'C', 'B', 'C'],&lt;br&gt;
        'Value': [10, 20, 15, 25, 30, 35]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Group by 'Category', calculate mean of 'Value', reset index, and rename column&lt;br&gt;
result = df.groupby('Category').agg({'Value': 'mean'}).reset_index().rename(columns={'Value': 'Mean_Value'})&lt;br&gt;
print(result)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; &lt;span class=&quot;faq-body&quot;&gt;Q: What is the significance of handling missing data?&lt;br&gt;A: Handling missing data is crucial for accurate analysis and modelling. Pandas offers methods like isnull(), fillna(), and dropna() for dealing with missing values effectively.&lt;/span&gt;&lt;/div&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;con&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In conclusion, becoming proficient with Pandas gives data workers a flexible framework for effectively managing, analyzing, and visualizing structured data in Python. Pandas' extensive capability allows users to address a broad range of &lt;strong&gt;data-related tasks&lt;/strong&gt;, from creating pivot tables and &lt;strong&gt;managing missing data&lt;/strong&gt; to executing sophisticated methods like time series analysis and method chaining. It improves &lt;strong&gt;data analysis&lt;/strong&gt; and &lt;strong&gt;manipulation &lt;/strong&gt;efficiency by promoting improved decision-making, getting &lt;strong&gt;deeper insights&lt;/strong&gt;, and optimising processes.&lt;/p&gt;
&lt;/section&gt;
&lt;p&gt;&lt;strong&gt;For Refering to Next Part of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1818/pandas-in-python-a-comprehensive-guide-part3&quot;&gt;Advancing with Pandas: Beyond the Basic&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For Referring to Previous Part of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1812/pandas-in-python-a-comprehensive-guide&quot;&gt;Pandas in Python: A Comprehensive Guide&lt;/a&gt;&lt;/p&gt;
</description>
<category>Adv Concepts</category>
<guid isPermaLink="true">https://coderlegion.com/1755/mastering-data-analysis-and-manipulation-with-pandas-a-comprehensive-guide</guid>
<pubDate>Mon, 31 Mar 2025 21:40:00 +0000</pubDate>
</item>
<item>
<title>Advancing with Pandas: Beyond the Basic</title>
<link>https://coderlegion.com/1684/advancing-with-pandas-beyond-the-basic</link>
<description>&lt;p&gt;In this article, we will look into Pandas, a core Python package for data analysis and manipulation. Now, we'll explore more complex topics to improve your &lt;strong&gt;data handling skills&lt;/strong&gt;, building on the fundamental concepts we covered in earlier sections. This thorough tutorial gives you the skills and information required to successfully handle challenging data problems, from &lt;strong&gt;performance optimization&lt;/strong&gt; to &lt;strong&gt;integrating Pandas&lt;/strong&gt; with external libraries and carrying out practical data analysis projects. Gaining proficiency in these sophisticated Pandas techniques will enable you to go deeper into your dataset analysis and extract even more value, whether you're an experienced data expert or just starting out.&lt;/p&gt;
&lt;p&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents: &lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#arr&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Performance Optimization with Pandas&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#index&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Pandas and External Libraries Integration&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#index1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Integrating Pandas with other Python libraries&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#index2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Converting between Pandas Data Frames and other data structures&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#fil&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Real-world Data Analysis Projects&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#con&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;
&lt;section&gt;&lt;a id=&quot;arr&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Performance Optimization with Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Enhancing the effectiveness and speed of data manipulation operations is known as performance optimization in Pandas, and it is particularly important when working with big datasets.&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Techniques for improving performance&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Vectorized Operations:&lt;/strong&gt; To efficiently conduct element-wise operations on arrays, vectorized operations make use of the NumPy library. Compared to similar procedures carried out using loops, these operations are substantially faster.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Python loops&lt;/strong&gt; should be avoided since they might be slow with huge datasets. For operations on complete columns or rows at once, use Pandas methods or vectorized operations instead. &lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Effective Functions&lt;/strong&gt; provided by pandas, such as pivot_table(), applymap(), groupby(), and map(), provide optimal performance and eliminate the need for additional functions and loops.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
# Generate a random number between 0 and 1&lt;br&gt;
random_num = np.random.rand()&lt;br&gt;
print(random_num)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Use the built-in Pandas functions and NumPy's vectorized operations to efficiently execute element-wise operations without resorting to sluggish Python loops. &lt;/span&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=8198876533685193889&quot; alt=&quot;&quot; width=&quot;390&quot; height=&quot;180&quot;&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Memory Optimization&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Pandas memory optimization is essential for managing big datasets effectively and minimizing memory consumption. There are various methods that can be used to accomplish this. Firstly, columns can be converted to more memory-efficient types like int32 or float32 without sacrificing precision by downcasting numeric data types using the &lt;code&gt;'astype()'&lt;/code&gt; method. Second, the Data Frame's memory footprint can be greatly reduced by eliminating any columns that are not needed for analysis. A different strategy is to use the category data type for categorical variables, which can significantly lower memory consumption—particularly for columns that have few unique values.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
import numpy as np&lt;br&gt;
# Creating a large DataFrame&lt;br&gt;
n_rows = 1000000&lt;br&gt;
data = {'A': np.random.randint(0, 100, n_rows),&lt;br&gt;
        'B': np.random.rand(n_rows)}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Vectorized operations&lt;br&gt;
df['C'] = df['A'] * 2 + df['B']  # Vectorized operation instead of a loop&lt;br&gt;
# Using efficient Pandas methods&lt;br&gt;
mean_value = df['A'].mean()  # Efficient computation of mean using Pandas method&lt;br&gt;
# Memory optimization&lt;br&gt;
df['A'] = df['A'].astype(np.int32)  # Downcasting to int32 for memory optimization&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;div class=&quot;div-red&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Be mindful of potential memory overhead generated by specific procedures while optimizing performance since this could result in higher memory usage and slower execution. &lt;/span&gt;&lt;/div&gt;
&lt;section&gt;&lt;a id=&quot;index&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Pandas and External Libraries Integration&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Pandas enhances Python's ability to analyze and manipulate data by integrating with a variety of external libraries with ease.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9297178741583285439&quot; alt=&quot;&quot; width=&quot;700&quot; height=&quot;300&quot;&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;section&gt;&lt;a id=&quot;index1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Integrating Pandas with other Python libraries&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Pandas may be used for a wider range of data analysis jobs and has more capability when it is integrated with other Python packages. Since Pandas Series and Data Frames are constructed on top of NumPy arrays, there is a common integration with NumPy that enables smooth interoperability between the two libraries. &lt;strong&gt;Effective vectorized operations&lt;/strong&gt; and &lt;strong&gt;mathematical calculations&lt;/strong&gt; on Pandas data structures are made possible by this integration. Furthermore, Pandas easily interacts with &lt;strong&gt;Seaborn &lt;/strong&gt;and &lt;strong&gt;Matplotlib &lt;/strong&gt;for data visualisation, providing easy ways to generate informative charts from Data Frame data. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
from sklearn.linear_model import LinearRegression&lt;br&gt;
# Sample DataFrame and column names (replace with your own)&lt;br&gt;
df = pd.DataFrame({&lt;br&gt;
    'Date': pd.date_range(start='2024-01-01', periods=6),&lt;br&gt;
    'Feature1': np.random.rand(6),&lt;br&gt;
    'Feature2': np.random.rand(6),&lt;br&gt;
    'Target': np.random.rand(6),&lt;br&gt;
    'Value': np.random.rand(6)&lt;br&gt;
})&lt;br&gt;
# Replace 'Feature1', 'Feature2', and 'Target' with your actual column names&lt;br&gt;
X = df[['Feature2', 'Feature1']].values&lt;br&gt;
y = df['Target'].values&lt;br&gt;
# Use Pandas plotting with Matplotlib&lt;br&gt;
df.plot(x='Date', y='Value', kind='line', ax=plt.gca())&lt;br&gt;
# Use Pandas DataFrame as input for Scikit-learn model&lt;br&gt;
model = LinearRegression()&lt;br&gt;
model.fit(df[['Feature1', 'Feature2']], df['Target'])&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;strong&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12012487059853380324&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;400&quot;&gt;&lt;/strong&gt;&lt;br&gt;
&lt;section&gt;&lt;a id=&quot;index2&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Converting between Pandas Data Frames and other data structures&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Interoperability with different data formats is made possible by the frequent process of converting between Pandas DataFrames and other data structures. For this reason, Pandas offers simple ways that make data sharing and integration across various data processing workflows easier to accomplish.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DataFrame to NumPy array:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Use the &lt;code&gt;'values'&lt;/code&gt; attribute of the DataFrame to obtain a NumPy array representation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Create a DataFrame&lt;br&gt;
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})&lt;br&gt;
# Convert DataFrame to NumPy array&lt;br&gt;
array = df.values&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;NumPy array to DataFrame:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pass the NumPy array as data to the DataFrame constructor, along with column names.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
import numpy as np&lt;br&gt;
# Create a NumPy array&lt;br&gt;
array = np.array([[1, 4], [2, 5], [3, 6]])&lt;br&gt;
# Convert NumPy array to DataFrame&lt;br&gt;
df = pd.DataFrame(array, columns=['A', 'B'])&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;DataFrame to dictionary:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Use the &lt;code&gt;'to_dict()'&lt;/code&gt; method of the DataFrame to convert it into a dictionary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Create a DataFrame&lt;br&gt;
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})&lt;br&gt;
# Convert DataFrame to dictionary&lt;br&gt;
dictionary = df.to_dict()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Dictionary to DataFrame:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Use the &lt;code&gt;'from_dict()'&lt;/code&gt; method of the DataFrame to create a DataFrame from a dictionary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Create a dictionary&lt;br&gt;
dictionary = {'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 4, 1: 5, 2: 6}}&lt;br&gt;
# Convert dictionary to DataFrame&lt;br&gt;
df = pd.DataFrame.from_dict(dictionary)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Process data in smaller parts using methods like chunking or streaming when working with large datasets that don't fit in memory to prevent memory issues. &lt;/span&gt;&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;fil&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Real-world Data Analysis Projects&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Practical challenges can be solved with Pandas, as demonstrated by real-world data analysis projects. Typically, these projects involve activities like modelling, data exploration, data cleaning, and visualization.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
from sklearn.linear_model import LinearRegression&lt;br&gt;
# Load data&lt;br&gt;
sales_data = pd.read_csv('/path/to/sales_data.csv')  # Provide your file path&lt;br&gt;
# Clean data&lt;br&gt;
sales_data.dropna(inplace=True)&lt;br&gt;
# Explore data&lt;br&gt;
total_sales = sales_data['Sales'].sum()&lt;br&gt;
average_sales = sales_data['Sales'].mean()&lt;br&gt;
# Visualize data&lt;br&gt;
sales_data['Date'] = pd.to_datetime(sales_data['Date'])&lt;br&gt;
sales_data.plot(x='Date', y='Sales', kind='line')&lt;br&gt;
plt.title('Sales Over Time')&lt;br&gt;
plt.xlabel('Date')&lt;br&gt;
plt.ylabel('Sales')&lt;br&gt;
# Model data&lt;br&gt;
model = LinearRegression()&lt;br&gt;
model.fit(sales_data[['Advertising']], sales_data['Sales'])&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The given script is essential for comprehending sales trends and assessing the effectiveness of advertizing campaigns in a real-world data research project. The main concepts of the script are stated below:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Importing and Cleaning Data:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;First, We have imported necessary libraries, such as scikit-learn, Matplotlib, and Pandas.&lt;/li&gt;
&lt;li&gt;It loads the sales information from a CSV file, most likely containing past sales records and associated advertising costs.&lt;/li&gt;
&lt;li&gt;In order to guarantee data integrity, data cleaning is carried out, and the dropna() method is used to eliminate missing values. This stage is essential to a precise analysis.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Analysing exploratory data:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Calculations are made to determine important metrics like average and total sales. These metrics help with subsequent analysis by offering preliminary insights into the dataset.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Data Visualization:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Using Matplotlib, the following example shows sales trends over time. Through the conversion of the date column to datetime format and the creation of a sales line plot, the evolution of sales across several time periods can be clearly visualized. The data's patterns, seasonality, and anomalies may be seen in this visualization.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Modeling:&lt;/strong&gt; &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The association between sales success and advertising cost is measured using linear regression modelling.&lt;/li&gt;
&lt;li&gt;Using the LinearRegression class from scikit-learn, the example applies a linear regression model to the data. This makes it possible to estimate the effects of variations in advertising expenditure on sales.&lt;/li&gt;
&lt;li&gt;Businesses can learn more about the efficacy of their advertising strategy and make data-driven decisions to maximise the performance of next campaigns by modelling the data.&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt;&lt;br&gt;Q: How can I speed up my code when working with large datasets in pandas?&lt;br&gt;A: Avoid using loops whenever possible, as they can be slow. Instead, use vectorized operations or pandas' built-in methods, such as apply(), map(), and groupby(), which are optimized for performance.&lt;br&gt;Q: Can I use Pandas with database libraries like SQLAlchemy or psycopg2 for database operations?&lt;br&gt;A: Absolutely! Pandas supports integration with database libraries such as SQLAlchemy for interacting with SQL databases and psycopg2 for PostgreSQL databases. You can use Pandas to read data from databases into DataFrames, perform data manipulation and analysis, and write the results back to the database.&lt;br&gt;Q: Is it possible to integrate Pandas with libraries like TensorFlow or PyTorch for deep learning?&lt;br&gt;A: Yes, Pandas can be used alongside deep learning frameworks like TensorFlow and PyTorch. You can preprocess and manipulate data with Pandas before feeding it into neural networks built using TensorFlow or PyTorch. Pandas' data manipulation capabilities complement the data preprocessing requirements of deep learning tasks.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In conclusion, Pandas is a &lt;strong&gt;flexible &lt;/strong&gt;Python &lt;strong&gt;data analysis&lt;/strong&gt; and &lt;strong&gt;manipulation &lt;/strong&gt;toolkit that provides strong capabilities for working with structured data. Pandas is a vital tool for data scientists, analysts, and researchers because of its &lt;strong&gt;user-friendly interface&lt;/strong&gt; and &lt;strong&gt;wide range of features&lt;/strong&gt;, which make it possible to efficiently clean, explore, and visualise datasets. You may improve your data workflows, glean insightful information, and facilitate well-informed decision-making by becoming proficient with Pandas.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For Referring to Previous Part1 of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1812/pandas-in-python-a-comprehensive-guide&quot;&gt;Pandas in Python: A Comprehensive Guide&lt;/a&gt;
&lt;p&gt;&lt;strong&gt;For Referring to Previous Part2 of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1817/pandas-in-python-a-comprehensive-guide-part2&quot;&gt;Mastering Data Analysis and Manipulation with Pandas: A Comprehensive Guide&lt;/a&gt;&lt;/section&gt;
&lt;/section&gt;
&lt;/section&gt;
</description>
<category>Adv Concepts</category>
<guid isPermaLink="true">https://coderlegion.com/1684/advancing-with-pandas-beyond-the-basic</guid>
<pubDate>Thu, 27 Mar 2025 10:52:14 +0000</pubDate>
</item>
<item>
<title>Pandas v3.x Defaults Copy-on-Write Feature - Get Used to it Early</title>
<link>https://coderlegion.com/400/pandas-v3-x-defaults-copy-on-write-feature-get-used-to-it-early</link>
<description>&lt;p&gt;Pandas supports Copy-on-Write, an optimization technique that helps improve memory use, particularly when working with large datasets.&lt;/p&gt;
&lt;p&gt;Starting from version 2.0 of Pandas, the Copy-on-Write (CoW) has taken effect but has not been fully implemented. Most of the optimizations that are possible through Copy-on-Write are supported.&lt;/p&gt;
&lt;h3 id=&quot;aim-of-copy-on-write&quot;&gt;Aim of Copy-on-Write&lt;/h3&gt;
&lt;p&gt;As the name suggests, the data will be copied when it is modified. What it means?&lt;/p&gt;
&lt;p&gt;When a DataFrame or Series shares the same data as the original, it will initially share the same memory for the data rather than creating a copy. When the data of either the original or new DataFrame is modified, a new copy of the data is created for the DataFrame that is being modified.&lt;/p&gt;
&lt;p&gt;This will efficiently save memory usage and improve performance when working with large datasets.&lt;/p&gt;
&lt;h3 id=&quot;enabling-cow-in-pandas&quot;&gt;Enabling CoW in Pandas&lt;/h3&gt;
&lt;p&gt;It is not enabled by default, so we need to enable it using the copy_on_write configuration option in Pandas.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Option1
pd.options.mode.copy_on_write = True
# Option2
pd.set_option(&quot;mode.copy_on_write&quot; : True)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can use any of the options to turn on CoW globally in your environment.&lt;/p&gt;
&lt;p&gt;Note: CoW will be enabled by default in Pandas 3.0, so get used to it early on.&lt;/p&gt;
&lt;h3 id=&quot;impact-of-cow-in-pandas&quot;&gt;Impact of CoW in Pandas&lt;/h3&gt;
&lt;p&gt;The CoW will disallow updating the multiple pandas objects at the same time. Here's how it will happen.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
subset = df[&quot;A&quot;]
subset.iloc[0] = 10
df
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With CoW, the above snippet will not modify df rather it modifies only the data of subset.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# df
AB
014
125
236

# subset
A
010
12
23
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;inplace-operations-will-not-work&quot;&gt;inplace Operations will Not Work&lt;/h3&gt;
&lt;p&gt;Similarly, the inplace operations will not work with CoW enabled, which directly modifies the original df.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
df[&quot;A&quot;].replace(1, 5, inplace=True)
df
--------------------
AB
014
125
236
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can see that df has remained unchanged and additionally, we will see a ChainedAssignmentError warning.&lt;/p&gt;
&lt;p&gt;The above operation can be performed in two different ways. One method is to avoid inplace, and another is to use inplace to directly modify the original df at the DataFrame level.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Avoid inplace
df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
df[&quot;A&quot;] = df[&quot;A&quot;].replace(1, 5)
df
--------------------
    AB
054
125
236

# Using inplace at DataFrame level
df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
df.replace({&quot;A&quot;: {2: 34}}, inplace=True)
df
--------------------
    AB
014
1345
236
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;chained-assignment-will-never-work&quot;&gt;Chained Assignment Will Never Work&lt;/h3&gt;
&lt;p&gt;When we modify the DataFrame or Series using multiple indexing operations in a single line of code, this is what we call the chained assignment technique.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# CoW disabled
with pd.option_context(&quot;mode.copy_on_write&quot;, False):
    df = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4], &quot;B&quot;: [5, 6, 7, 8]})
    df[&quot;B&quot;][df['A'] &amp;gt; 2] = 10
df
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The above code snippet is trying to change column B from the original df where column A is greater than 2. It means the value at the 2nd and 3rd index in column B will be modified.&lt;/p&gt;
&lt;p&gt;Since the CoW is disabled, this operation is allowed, and the original df will be modified.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;    AB
015
126
2310
3410
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But, this will never work with CoW enabled in pandas.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# CoW enabled
df = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4], &quot;B&quot;: [5, 6, 7, 8]})
df[&quot;B&quot;][df[&quot;A&quot;] &amp;gt; 2] = 10
df
--------------------
    AB
015
126
237
348
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead, with copy-on-write, we can use .loc to modify the df using multiple indexing conditions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# CoW enabled
df = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4], &quot;B&quot;: [5, 6, 7, 8]})
df.loc[(df[&quot;A&quot;] == 1) | (df[&quot;A&quot;] &amp;gt; 3), &quot;B&quot;] = 100
df
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will modify column B where column A is either 1 or greater than 3. The original df will look like the following.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;AB
01100
126
237
34100
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;read-only-arrays&quot;&gt;Read-only Arrays&lt;/h3&gt;
&lt;p&gt;When a Series or DataFrame is accessed as a NumPy array, that array will be read-only if the array shares the same data with the initial DataFrame or Series.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4], &quot;B&quot;: ['5', '6', '7', '8']})
arr = df.to_numpy()
arr
--------------------
array([[1, '5'],
       [2, '6'],
       [3, '7'],
       [4, '8']], dtype=object)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above code snippet, arr will be a copy because df contains two different types of arrays (int and str). We can perform modifications on the arr.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;arr[1, 0] = 10
arr
--------------------
array([[1, '5'],
       [10, '6'],
       [3, '7'],
       [4, '8']], dtype=object)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Take a look at this case.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3, 4], &quot;B&quot;: [5, 6, 7, 8]})
arr = df.to_numpy()
arr
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The DataFrame df has only one NumPy array (array of same data types), so arr shares the data with df. This means arr will be read-only and cannot be modified inplace.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;print(arr.flags.writeable)
arr[0,0] = 10
arr
--------------------
False
ValueError: assignment destination is read-only
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;lazy-copy-mechanism&quot;&gt;Lazy Copy Mechanism&lt;/h3&gt;
&lt;p&gt;When two or more DataFrames share the same data, the copies will not be created immediately.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
df2 = df.reset_index(drop=True)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both df and df2 shares the same reference in the memory as both share the same data. The copy mechanism will trigger only when any of the DataFrame is modified.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df2.iloc[0, 0] = 10
print(df2)
print(df)
--------------------
    A  B
0  10  4
1   2  5
2   3  6
   A  B
0  1  4
1  2  5
2  3  6
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But this is not necessary, if we don't want initial df, we can simply reassign it to the same variable (df) and this process will create a new reference. This will avoid the copy-on-write process.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
print(&quot;Initial reference: &quot;,id(df))
df = df.reset_index(drop=True)
print(&quot;New reference: &quot;,id(df))
df.iloc[0, 0] = 10
print(df)
--------------------
Initial reference:  138400246865760
New reference:      138400246860336
    A  B
0  10  4
1   2  5
2   3  6
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This same optimization (lazy copy mechanism) is added to the methods that don't require a copy of the original data.&lt;/p&gt;
&lt;p&gt;DataFrame.rename()&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]})
df.rename(columns={&quot;A&quot;: &quot;X&quot;, &quot;B&quot;: &quot;Y&quot;})
--------------------
XY
014
125
236
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When CoW is enabled, this method returns the original DataFrame rather than creating an entire copy of the data, unlike the regular execution.&lt;/p&gt;
&lt;p&gt;DataFrame.drop() for axis=1&lt;/p&gt;
&lt;p&gt;Similarly, the same mechanism is implemented for DataFrame.drop() for axis=1 (axis='columns').&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6], &quot;C&quot;: [7, 8, 9]})
df.drop([&quot;A&quot;], axis=1)
--------------------
BC
047
158
269
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;conclusion-1&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;Pandas will by default implement Copy-on-Write (CoW) in version 3.0. All these optimizations that are compliant with CoW will lead to efficient memory and resource management when working with large datasets.&lt;/p&gt;
&lt;p&gt;This will reduce unpredictable or inconsistent behavior and greatly maximize performance.&lt;/p&gt;
&lt;p&gt;Other articles you might be interested in if you liked this one&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/multiple-datasets-integration-using-pandas&quot;&gt;Merge, combine, and concatenate multiple datasets using pandas.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/find-and-delete-duplicate-rows-from-dataset&quot;&gt;Find and delete duplicate rows from the dataset using pandas.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/find-and-delete-mismatched-columns-from-dataframes-using-pandas&quot;&gt;Find and Delete Mismatched Columns From DataFrames Using pandas.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/tempfile-in-python&quot;&gt;Create temporary files and directories using tempfile module in Python.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/render-images-from-flask&quot;&gt;Upload and display images on the frontend using Flask.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;✅&lt;a rel=&quot;nofollow&quot; href=&quot;https://geekpython.in/impact-of-learning-rates-on-ml-and-dl-models&quot;&gt;How does the learning rate affect the ML and DL models?&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;That's all for now&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Keep Coding✌✌&lt;/strong&gt;&lt;/p&gt;
</description>
<category>Best Practices</category>
<guid isPermaLink="true">https://coderlegion.com/400/pandas-v3-x-defaults-copy-on-write-feature-get-used-to-it-early</guid>
<pubDate>Tue, 07 Jan 2025 06:13:57 +0000</pubDate>
</item>
<item>
<title>Data Visualization with Python: Using Matplotlib and Seaborn</title>
<link>https://coderlegion.com/385/data-visualization-with-python-using-matplotlib-and-seaborn</link>
<description>&lt;p&gt;Effective data analysis and science depend on data visualization. It aids in the &lt;strong&gt;identification of patterns&lt;/strong&gt;, &lt;strong&gt;developments&lt;/strong&gt;, and &lt;strong&gt;linkages in data&lt;/strong&gt;, enabling well-informed choices. Python packages like seaborn and matplotlib facilitate data visualization.&lt;/p&gt;
&lt;p&gt;This article teaches you &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/248/mastering-data-visualization-with-matplotlib-in-python?show=248#q248&quot;&gt;matplotlib&lt;/a&gt; and seaborn while highlighting the significance of data visualization. You'll discover how to extract insightful information, produce illuminating visualizations, and effectively convey data-driven conclusions.&lt;/p&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Getting Started with matplotlib&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://matplotlib.org/stable/users/getting_started/&quot;&gt;Matplotlib&lt;/a&gt; is a well-liked Python package for making static, animated, and interactive visualizations.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Installing with pip&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Use pip to install matplotlib by running the following command.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;pip install matplotlib&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After installation, use this command to view the Pandas version:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib&lt;br&gt;
print(matplotlib.__version__)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; Use virtual environments to keep your matplotlib installs apart and your dependencies organised across many projects.&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;1. Basic Plotting:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Matplotlib offers various plot types, including: Line plots: plot(), Scatter plots: scatter(), Bar plots: bar().&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A. Line plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
x = [1, 2, 3]&lt;br&gt;
y = [2, 4, 6]&lt;br&gt;
plt.plot(x, y)&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11759458743871917592&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;370&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;B: Scatter Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
x = [1, 2, 3, 4, 5]&lt;br&gt;
y = [2, 3, 5, 7, 11]&lt;br&gt;
plt.plot(x, y, color='blue', linestyle='-', marker='o', label='Line Plot')&lt;br&gt;
plt.scatter(x, y, color='red', marker='o', label='Scatter Plot')&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=6199798886000447528&quot; alt=&quot;&quot; width=&quot;500&quot; height=&quot;370&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Customizing Plot Appearance:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Customize your plots with: Labels: xlabel(), ylabel(), Titles: title(), Colors: color, Styles: style.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
x = [1, 2, 3, 4, 5]&lt;br&gt;
y = [2, 3, 5, 7, 11]&lt;br&gt;
plt.plot(x, y)&lt;br&gt;
plt.xlabel('X-axis', fontsize=12, fontweight='bold', color='blue')&lt;br&gt;
plt.ylabel('Y-axis', fontsize=12, fontweight='bold', color='blue')&lt;br&gt;
plt.xticks(fontsize=10, rotation=45)&lt;br&gt;
plt.yticks(fontsize=10)&lt;br&gt;
plt.legend(['Data'], loc='upper left', fontsize=10)&lt;br&gt;
plt.text(3, 6, 'Important point', fontsize=10, color='red')&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16923467982169904936&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Exploring Advanced Features of matplotlib&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;We'll explore the essential procedures for using matplotlib's pyplot interface to create simple plots. Here's a thorough description and an example of the code:&lt;/p&gt;
&lt;h3&gt;Multiple Axes and Subplots&lt;/h3&gt;
&lt;p&gt;You can make complicated figures with numerous subplots and axes within a single figure using matplotlib's &quot;Multiple Axes and Subplots&quot; functionality.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;plt.subplots()&lt;/strong&gt;: This function is used to produce a figure with several subplots grouped in a grid format. It yields a multidimensional array of axis objects and a figure object. Axes objects are used to represent each subplot and can be used to customize or plot data for each subplot.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;axes.plot()&lt;/strong&gt;: After using plt.subplots() to generate subplots, you may plot data on particular axes by using the axes object's plot() method. With this approach, you may individually alter each subplot's appearance and attributes, including line styles, colours, markers, and labels.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
import numpy as np&lt;br&gt;
fig, axs = plt.subplots(2, 2)&lt;br&gt;
x = np.linspace(0, 2*np.pi, 400)&lt;br&gt;
axs[0, 0].plot(x, np.sin(x))&lt;br&gt;
axs[0, 1].plot(x, np.cos(x))&lt;br&gt;
axs[1, 0].plot(x, np.sin(x**2))&lt;br&gt;
axs[1, 1].plot(x, np.cos(x**2))&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14672149811722259518&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;
&lt;p&gt;&lt;strong&gt;Saving Plots:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
x = [1, 2, 3, 4, 5]&lt;br&gt;
y = [2, 3, 5, 7, 11]&lt;br&gt;
plt.plot(x, y)&lt;br&gt;
# Saving the plot as a PDF file&lt;br&gt;
plt.savefig('plot.pdf')&lt;br&gt;
plt.savefig('plot.svg')&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Introduction to seaborn&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Based on matplotlib, &lt;a rel=&quot;nofollow&quot; href=&quot;https://seaborn.pydata.org/&quot;&gt;seaborn&lt;/a&gt; is a Python data visualization package that offers a high-level interface for creating visually appealing and educational statistical visuals. It makes it simple to produce educational and captivating visualizations by concentrating on statistical analysis visualization.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Installing with pip&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Run the following command to install seaborn using pip.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;pip install seaborn&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After installation, use this command to view the &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/216/pandas-in-python-a-comprehensive-guide?show=216#q216&quot;&gt;Pandas&lt;/a&gt; version:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn&lt;br&gt;
print(seaborn.__version__)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Advantages of seaborn over matplotlib&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;High-level interface&lt;/strong&gt;: To create intricate visualizations, seaborn offers an easier-to-use API.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Statistical graphics&lt;/strong&gt;: Seaborn is perfect for data exploration and visualization because it was created especially for statistical analysis.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Aesthetics&lt;/strong&gt;: Seaborn's default colour schemes and style selections produce plots that are aesthetically pleasing and appear well-designed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Integration with Pandas&lt;/strong&gt;: Seaborn's smooth integration with Pandas DataFrames facilitates data processing and visualization.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; Python's intuitive statistical visuals might help you streamline your data visualization process&lt;span class=&quot;alert-body&quot;&gt;. &lt;/span&gt;&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Exploring seaborn's Capabilities&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;A variety of features are available from seaborn to improve your visualizations, such as:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Standard themes for a polished appearance&lt;/li&gt;
&lt;li&gt;colour schemes for dependable and eye-catching hues&lt;/li&gt;
&lt;li&gt;Exploring categorical data with categorical plots&lt;/li&gt;
&lt;li&gt;Relationship charts to illustrate the connections between factors&lt;/li&gt;
&lt;/ol&gt;
&lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Using Seaborn's Default Themes&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;p&gt;Seaborn comes with several default themes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import matplotlib.pyplot as plt&lt;br&gt;
import seaborn as sns&lt;br&gt;
# Set the default theme&lt;br&gt;
sns.set_theme()&lt;br&gt;
sns.stripplot(x=[1, 2, 3, 4])&lt;br&gt;
plt.title(&quot;Default Theme&quot;)&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15597876653203244013&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;&lt;/p&gt;
&lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Using Colour Palettes&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;p&gt;Seaborn provides several colour palettes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sns.color_palette(&quot;husl&quot;, 8)  # Use the husl palette with 8 colors&lt;br&gt;
sns.color_palette(&quot;RdBu&quot;, 8)  # Use the RdBu palette with 8 colors&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Categorical Plots&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
&lt;p&gt;The sns.catplot() function from seaborn produces eye-catching and educational category graphs, such as: Swarm plots, Box plots, Violin plots. It makes it possible to specify the x and y data axes using, correspondingly, arguments like x and y. The kind argument determines the sort of categorical plot (e.g., &quot;strip&quot; or &quot;swarm&quot;), while the data parameter makes dataset provision easier. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Swarm Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
tips = sns.load_dataset(&quot;tips&quot;)&lt;br&gt;
sns.catplot(x=&quot;sex&quot;, y=&quot;total_bill&quot;, data=tips, kind=&quot;swarm&quot;)&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9016395722868110244&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Box Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
tips = sns.load_dataset(&quot;tips&quot;)&lt;br&gt;
sns.catplot(x=&quot;sex&quot;, y=&quot;total_bill&quot;, data=tips, kind=&quot;box&quot;)&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17649580600953587769&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Violin Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
tips = sns.load_dataset(&quot;tips&quot;)&lt;br&gt;
sns.catplot(x=&quot;sex&quot;, y=&quot;total_bill&quot;, data=tips, kind=&quot;violin&quot;)&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Relationship Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Seaborn's sns.relplot() function visualizes relationships between variables. The dataset provisioning process also makes use of the data parameter. Data subsets are distinguished using parameters like hue, col, and row. Plot types like &quot;scatter&quot; and &quot;line&quot; are specified by the kind option, which makes it easier to visualize variable relationships.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Scatter Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sns.relplot(x=&quot;x&quot;, y=&quot;y&quot;, data=df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Line Plot:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;sns.relplot(x=&quot;x&quot;, y=&quot;y&quot;, data=df , kind=&quot;line&quot;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Advanced Data Visualization Techniques&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Pair Plots&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Pair plots are a great way to visualize relationships between multiple &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/201/python-variables-and-data-types?show=201#q201&quot;&gt;variables&lt;/a&gt;. Seaborn's sns.pairplot() function creates a matrix of pairwise plots, showing the relationship between each pair of variables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
# Load the iris dataset&lt;br&gt;
iris = sns.load_dataset(&quot;iris&quot;)&lt;br&gt;
# Create a pair plot&lt;br&gt;
sns.pairplot(iris)&lt;br&gt;
# Show the plot&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Facet Grids&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;For more effective comparison, faceted grids are a fantastic tool for creating multi-plot grids. Seaborn's social network. A grid of plots is produced using the FacetGrid() function, each of which displays a distinct portion of the data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
# Load the tips dataset&lt;br&gt;
tips = sns.load_dataset(&quot;tips&quot;)&lt;br&gt;
# Create a facet grid&lt;br&gt;
g = sns.FacetGrid(tips, col=&quot;sex&quot;, row=&quot;smoker&quot;)&lt;br&gt;
# Map a plot to each subset&lt;br&gt;
g.map(sns.histplot, &quot;total_bill&quot;, alpha=0.7)&lt;br&gt;
# Show the plot&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9975442752338688993&quot; alt=&quot;&quot; width=&quot;517&quot; height=&quot;465&quot;&gt;&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Heatmaps&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;A useful tool for visualizing correlation matrices is a heatmap. A heatmap can be produced from a dataset or correlation matrix using seaborn's sns.heatmap() method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import seaborn as sns&lt;br&gt;
import matplotlib.pyplot as plt&lt;br&gt;
import numpy as np&lt;br&gt;
import pandas as pd&lt;br&gt;
# Load the flights dataset&lt;br&gt;
flights = sns.load_dataset(&quot;flights&quot;)&lt;br&gt;
# Select only numerical columns&lt;br&gt;
flights_num = flights.select_dtypes(include=[np.number])&lt;br&gt;
# Create a heatmap of the correlation matrix&lt;br&gt;
sns.heatmap(flights_num.corr(), annot=True, cmap=&quot;YlGnBu&quot;)&lt;br&gt;
# Show the plot&lt;br&gt;
plt.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Real-World Examples&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Let's analyse and display some data from a CSV file that contains employee details.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Read the CSV file into a DataFrame
&lt;br&gt;data = pd.read_csv('data.csv')&lt;br&gt;
# Display the first few rows of the DataFrame
&lt;br&gt;print(data.head())&lt;br&gt;
# Print information about the DataFrame
&lt;br&gt;print(data.info())&lt;br&gt;
# Display descriptive statistics of the DataFrame
&lt;br&gt;print(data.describe())&lt;br&gt;
# Plot a histogram of the 'age' column
&lt;br&gt;plt.hist(data['age'])&lt;br&gt;
# Plot a count of employees per department
&lt;br&gt;sns.countplot(x='department', data=data)&lt;br&gt;
# Plot a scatterplot of age vs salary
&lt;br&gt;sns.scatterplot(x='age', y='salary', data=data)&lt;br&gt;
# Calculate the average salary per department
&lt;br&gt;dept_avg_salary = data.groupby('department')['salary'].mean()&lt;br&gt;
# Select employees with salaries greater than $100,000
&lt;br&gt;high_salary_employees = data[data['salary'] &amp;gt; 100000]&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This example provides a basic demonstration, illustrating the use of seaborn and matplotlib for visualizing real-world datasets. There are a plethora of additional ways to study and visualize your data based on the particular questions you wish to address!&lt;/p&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Additional visualization libraries&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Plotly&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Plotly is a flexible Python module that works well for interactive plotting, easily meeting the needs of web dashboards and data exploration. It is a well-liked solution for many applications due to its wide range of chart options, which support both static and interactive displays.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import plotly.express as px&lt;br&gt;
import pandas as pd&lt;br&gt;
df = pd.DataFrame({&lt;br&gt;
    &quot;x&quot;: [1, 2, 3, 4, 5],&lt;br&gt;
    &quot;y&quot;: [2, 4, 6, 8, 10]&lt;br&gt;
})&lt;br&gt;
fig = px.line(df, x=&quot;x&quot;, y=&quot;y&quot;, title=&quot;Plotly Line Chart&quot;)&lt;br&gt;
fig.show()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17558324980380248367&quot; alt=&quot;&quot; width=&quot;750&quot; height=&quot;400&quot;&gt;&lt;br&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Bokeh&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Bokeh is a Python interactive visualization framework that works well for web-based plots and can be embedded into programs like Flask or Django. It includes capabilities for hovering, panning, and zooming.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;from bokeh.plotting import figure, output_notebook, show&lt;br&gt;
# Sample data&lt;br&gt;
x = [1, 2, 3, 4, 5]&lt;br&gt;
y = [2, 4, 6, 8, 10]&lt;br&gt;
# Plotting with Bokeh&lt;br&gt;
output_notebook()&lt;br&gt;
p = figure(title=&quot;Bokeh Line Plot&quot;)&lt;br&gt;
p.line(x, y)&lt;br&gt;
show(p)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4690874742944945395&quot; alt=&quot;&quot; width=&quot;517&quot; height=&quot;465&quot;&gt;&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; &lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;Q: What are data visualization techniques?&lt;br&gt;A: Data visualization techniques include charts (line, bar, or pie), plots (bubble or scatter), diagrams, maps (heat maps, geographic maps, etc.), and matrices.&lt;br&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In this article, we've covered the principles of matplotlib and seaborn data visualization. We have looked at: &lt;strong&gt;Configuring and personalizing plots&lt;/strong&gt;; &lt;strong&gt;displaying several data formats&lt;/strong&gt; (numerical, categorical, and time series); &lt;strong&gt;developing interactive plots&lt;/strong&gt;; and using &lt;strong&gt;data visualization &lt;/strong&gt;on actual datasets. &lt;/p&gt;
&lt;p&gt;Understanding and sharing insights is made easier with the help of data visualization. Your data may have hidden trends, patterns, and correlations that you can find by using matplotlib and seaborn. Don't be scared to experiment, investigate, and visualize; you might be surprised by the insights you find!&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;For more reference on matplotlib and seaborn:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Matplotlib Official Wensite:&lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://matplotlib.org/&quot;&gt;Matplotlib Official Website&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Seaborn Official Website:&lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://seaborn.pydata.org/l&quot;&gt;Seaborn: statistical data visualization&lt;/a&gt;&lt;/p&gt;
&lt;/section&gt;
</description>
<category>Getting Started</category>
<guid isPermaLink="true">https://coderlegion.com/385/data-visualization-with-python-using-matplotlib-and-seaborn</guid>
<pubDate>Sat, 06 Jul 2024 06:51:20 +0000</pubDate>
</item>
<item>
<title>Resolved: Attributeerror: 'dataframe' object has no attribute 'reshape'</title>
<link>https://coderlegion.com/367/resolved-attributeerror-dataframe-object-has-no-attribute-reshape</link>
<description>&lt;p&gt;Encountering the &lt;code&gt;AttributeError 'DataFrame' object has no attribute 'reshape'&lt;/code&gt; is common when using Pandas in &lt;strong&gt;Python&lt;/strong&gt;. It happens due to the absence of the reshape attribute within the DataFrame class, especially during reshaping operations. However, you can resolve this by using alternative methods like the reshape function from &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/&quot;&gt;numpy&lt;/a&gt; or &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/&quot;&gt;pandas&lt;/a&gt; methods like &lt;code&gt;pivot_table&lt;/code&gt; or &lt;code&gt;stack&lt;/code&gt;. These options effectively manipulate DataFrame objects, eliminating the AttributeError.&lt;/p&gt;
&lt;h2 id=&quot;why-did-this-error-occur-&quot;&gt;Why did this error occur?&lt;/h2&gt;
&lt;p&gt;The error occurred because the &lt;code&gt;.reshape()&lt;/code&gt; method was erroneously applied to a &lt;code&gt;DataFrame&lt;/code&gt; object, which doesn't support this operation. Attempting to reshape a single column selection without converting it into a DataFrame resulted in a Series object, which also lacks the &lt;code&gt;reshape()&lt;/code&gt; method. Additionally, DataFrame selection processes that didn't maintain the DataFrame structure led to applying a method that doesn't exist for Series objects.&lt;/p&gt;
&lt;h3 id=&quot;recreating-the-scenario&quot;&gt;Recreating the Scenario&lt;/h3&gt;
&lt;p&gt;To recreate this scenario, try applying the &lt;code&gt;.reshape()&lt;/code&gt; method directly to a DataFrame object or to a Series object resulting from a single column selection without proper DataFrame conversion. Additionally, ensure that the DataFrame selection process doesn't maintain the DataFrame structure, leading to the application of a method that doesn't exist for Series objects.&lt;/p&gt;
&lt;h3 id=&quot;example-1&quot;&gt;Example&lt;/h3&gt;
&lt;p&gt;Consider a scenario where you have a pandas DataFrame named &lt;code&gt;df&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
# Creating a DataFrame
data = {'A': [1, 2, 3],
        'B': [4, 5, 6]}
df = pd.DataFrame(data)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above code, shape of df(&lt;code&gt;df.shape&lt;/code&gt;) is : &lt;code&gt;(3, 2)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Now, let's say you want to reshape this DataFrame using the reshape() method:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Trying to reshape the DataFrame
reshaped_df = df.reshape(2, 3)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here's where the problem arises! When you run this code, you encounter the &lt;code&gt;AttributeError: 'DataFrame' &lt;/code&gt;object has no attribute 'reshape' error.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;OUTPUT ERROR&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5771900592786157763&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;When you try to reshape a DataFrame using the &lt;code&gt;reshape()&lt;/code&gt; method, pandas doesn't recognize &lt;code&gt;reshape()&lt;/code&gt; as a valid method for DataFrames. The &lt;code&gt;reshape()&lt;/code&gt; method is native to NumPy arrays, not pandas DataFrames.&lt;/p&gt;
&lt;h2 id=&quot;what-does-the-error-mean-&quot;&gt;What does the error mean?&lt;/h2&gt;
&lt;p&gt;Alright, so what's this error all about? Basically, when you see AttributeError: 'DataFrame' object has no attribute 'reshape', it's pandas politely saying, &quot;Hey, I'm a DataFrame, not a NumPy array! I don't know what you want me to do with this reshape() thing.&quot; In simpler terms, it's like trying to teach your dog to juggle – it's just not gonna happen because that's not what dogs do!&lt;/p&gt;
&lt;p&gt;&lt;em&gt;In technical words, this error message indicates that the DataFrame object (df) doesn't have an attribute called reshape. In other words, you're trying to use a method (&lt;code&gt;reshape()&lt;/code&gt;) that doesn't exist for DataFrame objects.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id=&quot;what-are-the-causes-of-the-error-&quot;&gt;What are the causes of the error?&lt;/h2&gt;
&lt;h3 id=&quot;1-dataframe-attribute-misinterpretation&quot;&gt;1. Dataframe Attribute Misinterpretation&lt;/h3&gt;
&lt;p&gt;This name encapsulates the scenario where a DataFrame object is treated as having an attribute (reshape) that it doesn't actually possess, leading to an AttributeError.&lt;/p&gt;
&lt;h3 id=&quot;problem&quot;&gt;PROBLEM&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Attempting to use reshape on a DataFrame directly
reshaped_df = df.reshape(2, 3)  # Causes AttributeError
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;solution&quot;&gt;SOLUTION&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(&quot;df : \n&quot;,df)

# Convert DataFrame to numpy array
array_df = df.values
print(&quot;\narray_df : &quot;, array_df)

# Reshape the numpy array
reshaped_array = array_df.reshape(2, 3)
print(&quot;\nreshaped_array : &quot;,reshaped_array)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;output&quot;&gt;OUTPUT&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1771281601914134466&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Utilize NumPy's Reshape Function&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;2-incorrect-method-chaining&quot;&gt;2. Incorrect Method Chaining&lt;/h3&gt;
&lt;p&gt;This cause describes the situation where incorrect method chaining is attempted on a DataFrame, resulting in an AttributeError.&lt;/p&gt;
&lt;h3 id=&quot;problem-1&quot;&gt;PROBLEM&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Incorrect method chaining
reshaped_df = df.groupby('A').reshape(2, 3)  # Causes AttributeError
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;solution-1&quot;&gt;SOLUTION&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Proper method chaining using pivot_table
reshaped_df = df.pivot_table(index='A', columns='B', aggfunc='size', fill_value=0)
print(&quot;reshaped_df : \n&quot;, reshaped_df)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;explanation&quot;&gt;Explanation&lt;/h4&gt;
&lt;pre&gt;&lt;code&gt;reshaped_df = df.pivot_table(index='A', columns='B', aggfunc='size', fill_value=0)
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;df&lt;/code&gt;: This is the DataFrame object that you're working with.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;pivot_table&lt;/code&gt;: This is a method provided by pandas DataFrame objects for reshaping data. It allows you to create a pivot table from the DataFrame's data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;index='A'&lt;/code&gt;: This specifies that the values in column 'A' will be used as the index (rows) of the pivot table.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;columns='B'&lt;/code&gt;: This specifies that the values in column 'B' will be used as the columns of the pivot table.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;aggfunc='size'&lt;/code&gt;: This specifies the aggregation function to be used. In this case, 'size' means that it will count the occurrences of each combination of 'A' and 'B' values.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;fill_value=0&lt;/code&gt;: This specifies the value to be filled in for missing combinations of 'A' and 'B' values. In this case, it's set to 0.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;reshaped_df&lt;/code&gt;: This is the variable where the resulting reshaped DataFrame will be stored.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Overall, this line of code takes the DataFrame &lt;code&gt;df&lt;/code&gt; and creates a pivot table from its data based on the specified &lt;code&gt;index ('A')&lt;/code&gt;, &lt;code&gt;columns ('B')&lt;/code&gt;, &lt;code&gt;aggregation function ('size')&lt;/code&gt;, and fill value (0 for missing combinations). The resulting pivot table is stored in the variable &lt;code&gt;reshaped_df&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;output-1&quot;&gt;OUTPUT&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7484390278300462807&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Familiarize Yourself with Pandas Methods&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;3-incorrect-dataframe-selection&quot;&gt;3. Incorrect DataFrame Selection&lt;/h3&gt;
&lt;p&gt;This cause occurs when trying to reshape a DataFrame selection that results in a Series object rather than a DataFrame.&lt;/p&gt;
&lt;h3 id=&quot;problem-2&quot;&gt;PROBLEM&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Selecting a single column which results in a Series
selected_column = df['A']

# Attempting to reshape the Series
reshaped_df = selected_column.reshape(3, 1)  # Causes AttributeError
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;solution-2&quot;&gt;SOLUTION&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd

# Creating a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(&quot;df : \n&quot;, df)

# Selecting a single column and converting it to a DataFrame
selected_column = df[['A']]  # Using double brackets to select as DataFrame

# Reshaping the DataFrame
reshaped_df = selected_column.values.reshape(3, 1)
print(&quot;\nreshaped_df : \n&quot;,reshaped_df)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;explanation-1&quot;&gt;Explanation&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;We create a DataFrame &lt;code&gt;df&lt;/code&gt; with two columns 'A' and 'B'.&lt;/li&gt;
&lt;li&gt;We select the &lt;code&gt;column 'A'&lt;/code&gt; using double brackets &lt;code&gt;[['A']]&lt;/code&gt;, which ensures that it's selected as a &lt;code&gt;DataFrame&lt;/code&gt; rather than a &lt;code&gt;Series&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;We use the &lt;code&gt;.values&lt;/code&gt; attribute to retrieve the underlying NumPy array from the selected DataFrame.&lt;/li&gt;
&lt;li&gt;We reshape the array to have 3 rows and 1 column using the &lt;code&gt;reshape()&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;The resulting reshaped array is assigned to the variable &lt;code&gt;reshaped_df&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The use of double brackets &lt;code&gt;[[]]&lt;/code&gt; ensures that the selected column remains a &lt;code&gt;DataFrame&lt;/code&gt;, allowing us to apply the &lt;code&gt;reshape()&lt;/code&gt; method without encountering the AttributeError.&lt;/p&gt;
&lt;h3 id=&quot;output-2&quot;&gt;OUTPUT&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11189027905201523996&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Check Documentation
&lt;br&gt;&lt;br&gt;Refer to the documentation of pandas and NumPy libraries for comprehensive guidance on reshaping operations and available methods. Documentation provides detailed explanations and examples that can aid in resolving errors and optimizing code.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;best-practices-1&quot;&gt;Best Practices&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h3&gt;&lt;strong&gt;DataFrame limitations&lt;/strong&gt;&lt;/h3&gt; Keep in mind that not all numpy functions are directly applicable to DataFrame objects due to differences in their underlying data structures.&lt;br&gt;
&lt;/li&gt;
&lt;li&gt;&lt;h3&gt;&lt;strong&gt;Method compatibility&lt;/strong&gt;&lt;/h3&gt; Ensure compatibility between the methods used and the specific DataFrame structure and data types to avoid potential errors.&lt;br&gt;
&lt;/li&gt;
&lt;li&gt;&lt;h3&gt;&lt;strong&gt;Data integrity&lt;/strong&gt;&lt;/h3&gt; Be cautious when reshaping data, as it may impact the integrity and interpretability of the original dataset. Consider the implications of reshaping operations on downstream analysis and visualization.&lt;br&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Be diligent in understanding the implications of DataFrame operations to ensure data integrity and accurate analysis.&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Make sure DataFrame methods are compatible with your data to avoid messing it up.&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;conclusion-2&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In summary, the &lt;code&gt;AttributeError: 'DataFrame'&lt;/code&gt; object has no attribute &lt;code&gt;'reshape'&lt;/code&gt; error occurs when attempting to use the reshape() method on a pandas DataFrame, which doesn't support this method. Understanding the difference between NumPy arrays and pandas DataFrames, as well as utilizing appropriate DataFrame methods like pivot() or melt(), can help avoid this error and efficiently manipulate data in pandas.&lt;/p&gt;
&lt;p&gt;Now, armed with this knowledge, you can reshape your pandas DataFrames without stumbling into the &lt;code&gt;reshape()&lt;/code&gt; method roadblock!&lt;/p&gt;
&lt;h2 id=&quot;references-1&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Pandas documentation:&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/&quot;&gt;https://pandas.pydata.org/docs/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;NumPy documentation: &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/&quot;&gt;https://numpy.org/doc/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/367/resolved-attributeerror-dataframe-object-has-no-attribute-reshape</guid>
<pubDate>Thu, 20 Jun 2024 21:46:10 +0000</pubDate>
</item>
<item>
<title>Pandas in Python: A Comprehensive Guide</title>
<link>https://coderlegion.com/216/pandas-in-python-a-comprehensive-guide</link>
<description>&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/user_guide/index.html#user-guide&quot;&gt;Pandas&lt;/a&gt; is a powerful Python library for &lt;strong&gt;analysis &lt;/strong&gt;and &lt;strong&gt;data manipulation&lt;/strong&gt;. It offers &lt;strong&gt;user-friendly&lt;/strong&gt;, &lt;strong&gt;high-performance&lt;/strong&gt; data structures and tools for handling structured data. Pandas' versatility and extensive feature set make it a popular choice for data research and analysis tasks.&lt;/p&gt;
&lt;p&gt;Series and DataFrame are the two primary data structures in Pandas.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;A series is a one-dimensional object that resembles an array and is made up of an array of labels called the index and an array of data.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;A data structure with two dimensions and labels that can have different kinds of columns is called a data frame. It can be compared to a SQL table or spreadsheet.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The &lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html&quot;&gt;Pandas Series&lt;/a&gt; adds labelled axes and missing data handling to &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/192/numpy-in-python-a-comprehensive-guide-easy?show=192#q192&quot;&gt;NumPy&lt;/a&gt; arrays. Data Frames are similar to dictionaries in that they handle diverse data types and use column names as keys. They provide effective row and column operations for manipulating structured data in Python.&lt;br&gt;In this article we will look at the Pandas Python data analysis library. We will go over its main characteristics, including performance optimization, handling of missing data, and intuitive data structures. Let's learn about Pandas' capabilities and improve your knowledge of data analysis.&lt;/p&gt;
&lt;p&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents:&amp;nbsp;&lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#intro&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Installing Pandas&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#num&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Panda Series&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#numpy&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Pandas Data Frames&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Data Manipulation with Pandas&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#arr1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Adding and Removing columns and rows&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Filtering and Sorting data&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr3&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Combining and Merging Data Frames&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr4&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Grouping and Aggregating data&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;&lt;a id=&quot;intro&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Installing Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Pip or Anaconda can be used to install Pandas.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Installing with pip&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;pip install pandas&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Installing with Anaconda&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Pandas comes pre-installed in the distribution if you use Anaconda. You may use conda to update it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;conda install pandas&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once installed, run the following command to see the Pandas version:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
print(pd.__version__)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; Use the robust indexing features of Pandas to effectively access and alter data.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Pandas Series&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Python's Pandas Series provide a flexible and effective method for handling one-dimensional labelled data. Different &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/201/python-variables-and-data-types?show=201#q201&quot;&gt;data types&lt;/a&gt;, such as texts, floats, integers, and even custom objects, can be stored in series.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Creating Series Objects&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You can use a variety of data structures, including Series and Data Frames, when constructing data objects in Python using Pandas. For instance, to create a Series object, you can use:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A. pd.Series()&lt;br&gt;&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;It shows a labelled, one-dimensional array with indices that can hold several kinds of data used to handle data with flexibility and ease of usage, enabling effective data processing and analysis.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
import numpy as np&lt;br&gt;
# Creating a Pandas Series from a list&lt;br&gt;
s = pd.Series([1, 3, 5, np.nan, 6, 8])&lt;br&gt;
# Creating a Pandas Series from a NumPy array&lt;br&gt;
arr = np.array([10, 20, 30, 40, 50])&lt;br&gt;
s_np = pd.Series(arr)&lt;br&gt;
# Creating a Pandas Series from a dictionary&lt;br&gt;
data = {'a': 0, 'b': 1, 'c': 2}&lt;br&gt;
s_dict = pd.Series(data)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1105812315454941718&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;370&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Accessing and manipulating Series data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There are several ways to access and work with Pandas Series, including slicing, indexing, and simple arithmetic operations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
s = pd.Series([1, 3, 5])&lt;br&gt;
# Accessing elements of a Series using index&lt;br&gt;
print(s[0]) &amp;nbsp;# Output: 1&lt;br&gt;
# Slicing a Series&lt;br&gt;
print(s[1:3]) &amp;nbsp;# Output: [3, 5]&lt;br&gt;
s_dict = pd.Series({&lt;span class=&quot;hljs-string&quot;&gt;'a'&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;2&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;'b'&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;4&lt;/span&gt;, &lt;span class=&quot;hljs-string&quot;&gt;'c'&lt;/span&gt;: &lt;span class=&quot;hljs-number&quot;&gt;6&lt;/span&gt;})&lt;br&gt;
# Basic arithmetic operations on Series&lt;br&gt;
s_add = s + s_dict &amp;nbsp;# Adding two Series with different indices&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=6202370942667980460&quot; alt=&quot;&quot; width=&quot;542&quot; height=&quot;280&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Methods for data alignment and missing data handling&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;When executing operations, Pandas automatically aligns data according to the index. Techniques like &lt;code&gt;'isnull()'&lt;/code&gt;,&lt;code&gt;'fillna()'&lt;/code&gt; ,and &lt;code&gt;'dropna()'&lt;/code&gt;can be used to deal with missing data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
s = pd.Series([1, 3, np.nan, 5])&lt;br&gt;
# Checking for missing values&lt;br&gt;
print(s.isnull())&lt;br&gt;
# Filling missing values with a specified value&lt;br&gt;
s_filled = s.fillna(0)&lt;br&gt;
# Dropping missing values&lt;br&gt;
s_dropped = s.dropna()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Pandas Data Frames&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Pandas Data Frame is a two-dimensional labelled data structure that is widely used for data manipulation and analysis in Python. It can be thought of as a table with rows and columns, where each column represents a different variable and each row represents a different observation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Creating DataFrames&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;'pd.DataFrame()'&lt;/code&gt; constructor can be used to create Data Frames from a variety of data sources, including CSV, Excel, SQL, and more, by providing in a dictionary or list of lists.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Creating a DataFrame from a dictionary&lt;br&gt;
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 'Age': [28, 35, 21, 45]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
print(df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5305427750060263285&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;300&quot;&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;p&gt;&lt;strong&gt;2. Understanding Data Frame structure&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Data Frames are made up of rows, indexes, and columns. Rows hold the actual data, whereas columns represent variables and indices provide row labels.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Accessing column names&lt;br&gt;
print(df.columns)&lt;br&gt;
# Accessing index&lt;br&gt;
print(df.index)&lt;br&gt;
# Accessing rows&lt;br&gt;
print(df.iloc[0]) &amp;nbsp;# Accessing the first row&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12460171665704861744&quot; alt=&quot;&quot; width=&quot;450&quot; height=&quot;370&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. Indexing and Selecting data&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Many indexing techniques, such as label-based, position-based, and Boolean indexing, can be used to retrieve data in Data Frames.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Label-based indexing&lt;br&gt;
print(df.loc[0, 'Name']) &amp;nbsp;# Accessing the 'Name' column of the first row&lt;br&gt;
# Position-based indexing&lt;br&gt;
print(df.iloc[0, 1]) &amp;nbsp;# Accessing the element in the first row and second column&lt;br&gt;
# Boolean indexing&lt;br&gt;
print(df[df['Age'] &amp;gt; 30]) &amp;nbsp;# Selecting rows where Age is greater than 30&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-blue&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Keep data types consistent between columns to prevent unexpected behaviour when performing operations. Verify and convert data types as needed to guarantee accuracy and compatibility. &lt;/span&gt;&lt;/div&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Data Manipulation with Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Pandas can be used to manipulate data in a variety of ways, including grouping and aggregating data, filtering and sorting data, joining and merging Data Frames, and more.&lt;/p&gt;
&lt;section&gt;&lt;a id=&quot;arr1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Adding and Removing columns and rows&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;You can add or remove rows and columns with &lt;code&gt;'df.dropna()'&lt;/code&gt; and&amp;nbsp;&lt;code&gt;'df.drop()'&lt;/code&gt;, among other ways.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
# Creating the initial DataFrame&lt;br&gt;
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 'Age': [28, 35, 21, 45]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Adding a new row using pd.concat()&lt;br&gt;
new_row = pd.DataFrame([['Tom', 33]], columns=['Name', 'Age'])&lt;br&gt;
df = pd.concat([df, new_row], ignore_index=True)&lt;br&gt;
print(&quot;DataFrame after adding a new row:&quot;)&lt;br&gt;
print(df)&lt;br&gt;
# Removing a row using pd.concat()&lt;br&gt;
df = pd.concat([df.iloc[1:]], ignore_index=True)&lt;br&gt;
print(&quot;\nDataFrame after removing the first row:&quot;)&lt;br&gt;
print(df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;section&gt;&lt;a id=&quot;arr2&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Filtering and sorting data&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Functions like &lt;code&gt;'df.filter()'&lt;/code&gt; and &lt;code&gt;'df.sort_values()'&lt;/code&gt;can be used to filter and sort Data Frames.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
# Sample DataFrame&lt;br&gt;
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 'Age': [25, 30, 35, 40]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Filtering rows based on conditions&lt;br&gt;
filtered_df = df[df['Age'] &amp;gt; 30]&lt;br&gt;
# Sorting by a column&lt;br&gt;
sorted_df = df.sort_values(by='Age', ascending=False)&lt;br&gt;
print(&quot;Filtered DataFrame:&quot;)&lt;br&gt;
print(filtered_df)&lt;br&gt;
print(&quot;\nSorted DataFrame:&quot;)&lt;br&gt;
print(sorted_df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;div class=&quot;div-red&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Large datasets may need computationally costly tasks like sorting, merging, or grouping. Employ the right Pandas techniques and algorithms to maximise performance. &lt;/span&gt;&lt;/div&gt;
&lt;section&gt;&lt;a id=&quot;arr3&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Combining and Merging Data Frames&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Data Frames can be joined together or merged using &lt;code&gt;'pd.concat()'&lt;/code&gt; and &lt;code&gt;'pd.merge()'&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd&lt;br&gt;
import numpy as np&lt;br&gt;
# Define DataFrame 1&lt;br&gt;
data1 = {'Name': ['Alice', 'Bob', 'Charlie'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;'Age': [25, 30, 22]}&lt;br&gt;
df1 = pd.DataFrame(data1)&lt;br&gt;
# Define DataFrame 2&lt;br&gt;
data2 = {'Name': ['David', 'Emily'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;'Age': [28, 35]}&lt;br&gt;
df2 = pd.DataFrame(data2)&lt;br&gt;
# Concatenating DataFrames horizontally&lt;br&gt;
df_concat_horizontal = pd.concat([df1, df2], axis=1)&lt;br&gt;
print(df_concat_horizontal)&lt;br&gt;
# Merging DataFrames based on multiple columns&lt;br&gt;
merged_df_multiple = pd.merge(df1, df2, on=['Name', 'Age'])&lt;br&gt;
print(merged_df_multiple)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;arr4&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;4. Grouping and Aggregating data&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Aggregation functions such as count(), mean(), and sum(), as well as &lt;code&gt;'df.groupby()'&lt;/code&gt;, can be used to group and aggregate data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import pandas as pd &lt;br&gt;
# Creating a DataFrame&lt;br&gt;
data = {'Category': ['A', 'B', 'A', 'B', 'A'],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 'Price': [10, 20, 15, 25, 12],&lt;br&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; 'Quantity': [5, 3, 4, 2, 6]}&lt;br&gt;
df = pd.DataFrame(data)&lt;br&gt;
# Grouping and aggregating data&lt;br&gt;
aggregated_df = df.groupby('Category').agg({'Price': 'sum', 'Quantity': 'mean'})&lt;br&gt;
print(&quot;Aggregated Data:&quot;)&lt;br&gt;
print(aggregated_df)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9723848123993878323&quot; alt=&quot;&quot; width=&quot;406&quot; height=&quot;350&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; &lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;Q: How do I perform data manipulation?&lt;br&gt;A: Pandas provides functions for selecting, filtering, merging, grouping, and aggregating data.&lt;br&gt;Q: What is the difference between loc and iloc?&lt;br&gt;A: loc is label-based indexing, used for selecting data by labels, while iloc is integer-location based indexing, used for selecting data by integer indices.&lt;/span&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;For Refering to Part2 of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1817/pandas-in-python-a-comprehensive-guide-part2&quot;&gt;Mastering Data Analysis and Manipulation with Pandas: A Comprehensive Guide &lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For Refering to Part3 of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://logiclair.org/1818/pandas-in-python-a-comprehensive-guide-part3&quot;&gt;Advancing with Pandas: Beyond the Basic &lt;/a&gt;&lt;/p&gt;
</description>
<category>More Libraries</category>
<guid isPermaLink="true">https://coderlegion.com/216/pandas-in-python-a-comprehensive-guide</guid>
<pubDate>Tue, 09 Apr 2024 21:57:18 +0000</pubDate>
</item>
<item>
<title>Numpy Tuitorial: Data Analysis for Data Science</title>
<link>https://coderlegion.com/202/numpy-tuitorial-data-analysis-for-data-science</link>
<description>&lt;h2&gt;1. Introduction to NumPy:&lt;/h2&gt;
&lt;p&gt;In the world of data science and machine learning, we analyze &lt;strong&gt;big sets of data&lt;/strong&gt; to make smart choices. A really helpful tool for this is called &lt;em&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/&quot;&gt;NumPy&lt;/a&gt;&lt;/em&gt;. It's a part of Python, a popular programming language. &lt;em&gt;NumPy&lt;/em&gt; helps us handle data in a special way. It's like a super tool that lets us organize and work with data really efficiently.&lt;/p&gt;
&lt;h3&gt;Importance and Usefulness:&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;NumPy&lt;/em&gt; efficiently handles large datasets, enabling tasks like &lt;strong&gt;data manipulation&lt;/strong&gt; and &lt;strong&gt;statistical analysis&lt;/strong&gt;. Mastery of &lt;em&gt;NumPy&lt;/em&gt; streamlines workflows and enhances data analysis, crucial for building robust machine learning models.&lt;/p&gt;
&lt;p&gt;This tutorial is a comprehensive guide to leveraging &lt;em&gt;NumPy&lt;/em&gt; for data analysis. Whether you're a novice or a seasoned practitioner, it equips you with essential skills to harness &lt;em&gt;NumPy&lt;/em&gt; effectively.&lt;/p&gt;
&lt;h3&gt;Lessons to Learn:&lt;/h3&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;em&gt;Understanding:&lt;/em&gt; Foundational concepts in data science facilitated by &lt;em&gt;NumPy&lt;/em&gt;.&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;Crafting:&lt;/em&gt; Creating and manipulating &lt;em&gt;NumPy&lt;/em&gt; arrays for data encapsulation.&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;Executing:&lt;/em&gt; Performing crucial calculations on &lt;em&gt;NumPy&lt;/em&gt; arrays for data analysis.&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;Application:&lt;/em&gt; Applying &lt;em&gt;NumPy&lt;/em&gt; skills to real-world data science challenges.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Prior &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.python.org/&quot;&gt;Python&lt;/a&gt; experience is recommended. While a background in &lt;strong&gt;matrix mathematics&lt;/strong&gt; is beneficial, it's not mandatory.&lt;/p&gt;
&lt;p&gt;For more information, refer to the &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/&quot;&gt;official NumPy documentation&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In this guide, we'll master data analysis with &lt;em&gt;NumPy&lt;/em&gt;, an essential Python library. &lt;em&gt;NumPy&lt;/em&gt;, short for Numerical Python, empowers analysts with multidimensional arrays and mathematical functions.&lt;/p&gt;
&lt;h3&gt;What is NumPy?&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;NumPy&lt;/em&gt; is like a superhero for handling numbers in Python! It's a special library that makes working with data super easy. Think of it as a &lt;strong&gt;powerful toolbox&lt;/strong&gt; full of tools specifically designed for crunching numbers and doing math. With &lt;em&gt;NumPy&lt;/em&gt;, we can create and manipulate arrays, which are like supercharged lists that can handle lots of data at once. This makes it perfect for tasks like data analysis, machine learning, and scientific computing.&lt;/p&gt;
&lt;h3&gt;Exploring NumPy and its capabilities:&lt;/h3&gt;
&lt;p&gt;NumPy's core object, the &lt;strong&gt;&lt;code&gt;ndarray&lt;/code&gt;&lt;/strong&gt;, serves as the foundation for its vast capabilities. This homogeneous multidimensional array allows for seamless manipulation and analysis of data. Whether it's &lt;strong&gt;performing mathematical computations&lt;/strong&gt; or &lt;strong&gt;handling large datasets&lt;/strong&gt;, NumPy provides the tools necessary for efficient data analysis.&lt;/p&gt;
&lt;h2&gt;2. Installing Numpy&lt;/h2&gt;
&lt;h3&gt;NumPy Installation Methods:&lt;/h3&gt;
&lt;p&gt;NumPy can be installed using various methods, including package managers and environments like pip, Anaconda, or virtual environments. Below are some common methods for installing NumPy:&lt;/p&gt;
&lt;h3&gt;1. Using pip:&lt;/h3&gt;
&lt;p&gt;You can install NumPy using &lt;a rel=&quot;nofollow&quot; href=&quot;https://pip.pypa.io/en/stable/&quot;&gt;pip&lt;/a&gt;, which is the standard package manager for Python. This method is suitable for users who prefer to manage their Python packages using pip. It is also convenient for installing NumPy in virtual environments or when you need to install additional Python packages along with NumPy:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pip install numpy
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;2. Using conda (Anaconda or Miniconda):&lt;/h3&gt;
&lt;p&gt;If you're using &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.anaconda.com/&quot;&gt;Anaconda&lt;/a&gt; or Miniconda, you can install NumPy using conda. Conda is a package manager and environment manager that is particularly useful for managing Python packages in data science and scientific computing environments. This method is recommended for users working with Anaconda distributions or those who prefer to manage their Python environments and packages using conda:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;conda install numpy
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Using system package managers:&lt;/h3&gt;
&lt;p&gt;Some operating systems provide package managers that allow you to install Python packages, including NumPy. This method is useful if you prefer to install NumPy through your system's package manager, ensuring compatibility and integration with other system packages. It is recommended for users who want NumPy to be installed system-wide and managed alongside other system packages:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;On Ubuntu/Debian:&lt;br&gt;
For installing on &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.ubuntu.com/&quot;&gt;Ubuntu&lt;/a&gt;, use,&lt;/p&gt;
&lt;p&gt;&lt;code&gt;sudo apt-get install python3-numpy&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On Fedora:&lt;br&gt;
For installing on &lt;a rel=&quot;nofollow&quot; href=&quot;https://getfedora.org/&quot;&gt;Fedora&lt;/a&gt;, use,&lt;/p&gt;
&lt;p&gt;&lt;code&gt;sudo dnf install numpy&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Consider using pip if you're working in a virtual environment or need to manage additional Python packages alongside NumPy.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2&gt;3. Setting up the environment:&lt;/h2&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/install/&quot;&gt;Installing NumPy&lt;/a&gt; is straightforward using pip, Python's package manager. With NumPy installed, you can swiftly import it into your scripts or interactive sessions, ready to harness its power for data analysis tasks.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pip install numpy

import numpy as np
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;4. NumPy Basics:&lt;/h2&gt;
&lt;h3&gt;Performing basic array operations:&lt;/h3&gt;
&lt;p&gt;Once arrays are in place, performing basic operations such as arithmetic operations, indexing, and slicing become essential techniques for data manipulation. NumPy provides intuitive syntax and optimized functions for these operations, enabling efficient processing of large datasets.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;a) Creating Arrays : &lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

# Creating arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;b) Arithmetic Operations : &lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Arithmetic operations
result = arr1 + arr2
print(&quot;\nResult : &quot;, result)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;c) Indexing and Slicing : &lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;# Indexing and slicing
print(arr1[0])      # Accessing the first element
print(arr2[1:])     # Slicing from the second element onwards
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10160493252202102454&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Utilize np.arange() for creating sequential arrays with specified start, stop, and step size easily.
&lt;/span&gt;
&lt;/div&gt;
&lt;h3&gt;Working with multidimensional arrays:&lt;/h3&gt;
&lt;p&gt;NumPy's support for multidimensional arrays is a cornerstone of its functionality. This feature enables data analysts to work with datasets of varying complexity, from simple matrices to high-dimensional tensors. With NumPy, you can &lt;strong&gt;reshape&lt;/strong&gt; arrays, &lt;strong&gt;stack&lt;/strong&gt; them together, and &lt;strong&gt;split&lt;/strong&gt; them into smaller arrays, providing unparalleled flexibility in data manipulation.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;a) Creating a 2D array : &lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Function Used&lt;/em&gt; - &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/generated/numpy.array.html&quot;&gt;numpy.array&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

# Creating a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(&quot;arr : &quot;, arr)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17253264280094338684&quot; alt=&quot;&quot;&gt; &lt;/p&gt;
&lt;h3&gt;b) Reshaping the array : &lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Function Used&lt;/em&gt; - &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/generated/numpy.reshape.html&quot;&gt;numpy.reshape&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Reshaping the array
reshaped_arr = arr.reshape(3, 2)
print(&quot;\nreshaped array : &quot;, reshaped_arr)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16886549567076588735&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;c) Transposing reshaped_arr to match the shape of arr : &lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Function Used&lt;/em&gt; - &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/generated/numpy.ndarray.T.html&quot;&gt;numpy.ndarray.T&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Transposing reshaped_arr to match the shape of arr
reshaped_arr_transposed = reshaped_arr.T
print(&quot;\nreshaped_arr_transposed : &quot;, reshaped_arr_transposed)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1135034611701643793&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;d) Stacking arrays vertically : &lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Function Used&lt;/em&gt; - &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/generated/numpy.vstack.html&quot;&gt;numpy.vstack&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Stacking arrays vertically
stacked_arr = np.vstack([arr, reshaped_arr_transposed])
print(&quot;\nstacked_array : &quot;, stacked_arr)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16224204987064354295&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;e) Splitting the array horizontally : &lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Function Used&lt;/em&gt; - &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html&quot;&gt;numpy.hsplit&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Splitting the array horizontally
split_arr = np.hsplit(stacked_arr, 3)
# Printing split_arr
print(&quot;\nsplit_array:&quot;)
for i, sub_array in enumerate(split_arr):
    print(f&quot;Part {i + 1}:&quot;)
    print(sub_array)
    print()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13643241000011712520&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2&gt;5. Advanced NumPy Techniques:&lt;/h2&gt;
&lt;p&gt;Advanced NumPy techniques involve leveraging the full power of NumPy for complex data analysis tasks. These techniques include advanced &lt;strong&gt;array manipulation&lt;/strong&gt;, &lt;strong&gt;broadcasting&lt;/strong&gt;, and utilizing &lt;strong&gt;universal functions&lt;/strong&gt; (ufuncs) for efficient element-wise operations on arrays of varying shapes and sizes.&lt;/p&gt;
&lt;h3&gt;Why Advanced NumPy Techniques?&lt;/h3&gt;
&lt;p&gt;While basic NumPy operations are essential for data analysis, mastering advanced techniques unlocks the full potential of NumPy, enabling you to efficiently handle more intricate datasets and perform sophisticated computations.&lt;/p&gt;
&lt;h3&gt;Expected Outcome:&lt;/h3&gt;
&lt;p&gt;By learning advanced NumPy techniques, you'll be equipped with the skills to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Perform complex mathematical operations on arrays.&lt;/li&gt;
&lt;li&gt;Efficiently manipulate and transform multidimensional arrays.&lt;/li&gt;
&lt;li&gt;Apply broadcasting to perform element-wise operations on arrays of different shapes.&lt;/li&gt;
&lt;li&gt;Utilize universal functions (&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/ufuncs.html&quot;&gt;ufuncs&lt;/a&gt;) for fast element-wise array operations.&lt;/li&gt;
&lt;li&gt;Implement &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/routines.array-manipulation.html&quot;&gt;advanced array manipulation techniques&lt;/a&gt; for data preprocessing and feature engineering.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt; Let's look at some most used advanced &lt;em&gt;NumPy&lt;/em&gt; techniques.&lt;/p&gt;
&lt;h3&gt;a) Broadcasting:&lt;/h3&gt;
&lt;p&gt;NumPy's &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/ufuncs.html&quot;&gt;broadcasting&lt;/a&gt; feature is a powerful tool for performing operations between arrays of different shapes. This capability eliminates the need for explicit looping over array elements, resulting in more concise and efficient code. Broadcasting enables data analysts to apply element-wise operations across arrays, even when their shapes differ, simplifying complex data manipulation tasks.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

# Broadcasting example
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([10, 20, 30])
print(&quot;\narr1 : &quot;,arr1)
print(&quot;\narr2 : &quot;,arr2 )

result = arr1 + arr2
print(&quot;\narr1 + arr2&quot;, result)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3543348219421935048&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;b) Universal functions (ufuncs):&lt;/h3&gt;
&lt;p&gt;NumPy provides universal functions (&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/routines.array-manipulation.html&quot;&gt;ufuncs&lt;/a&gt;) for performing element-wise operations on arrays. These functions are highly optimized and vectorized, resulting in faster execution compared to traditional looping constructs. By leveraging ufuncs, data analysts can efficiently apply mathematical functions, such as exponentiation and trigonometric operations, to entire arrays, enhancing productivity and performance in data analysis workflows.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

# Universal functions example
arr = np.array([1, 2, 3])
print(&quot;arr : &quot;, arr)

result = np.square(arr)
print(&quot;\nresult : &quot;, result)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14960397590347048628&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;c) Array manipulation:&lt;/h3&gt;
&lt;p&gt;NumPy offers advanced techniques for modifying array shapes and structures, providing data analysts with greater control over their data. Whether it's transposing arrays, flattening them, or rearranging their elements, NumPy's array manipulation capabilities enable flexible and efficient data processing. These techniques are invaluable for tasks such as data cleaning, preprocessing, and feature engineering, contributing to more robust and accurate data analyses.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CODE&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import numpy as np

# Array manipulation example
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(&quot;arr : \n&quot;, arr)

# Transposing the array
transposed_arr = arr.T
print(&quot;\ntransposed array : \n&quot;, transposed_arr)

# Flattening the array
flattened_arr = arr.flatten()
print(&quot;\nflattened array :  : &quot;, flattened_arr)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;OUTPUT&lt;/em&gt;&lt;br&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2716952329868588857&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;By mastering these basic and advanced techniques in NumPy, you'll be well-equipped to handle various data analysis tasks efficiently. Stay tuned for the next parts of this comprehensive guide, where we'll delve deeper into more advanced topics.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Harness NumPy's broadcasting for seamless element-wise operations between arrays of varying shapes.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2&gt;6. Case Studies and Real-World Applications:&lt;/h2&gt;
&lt;h3&gt;Practical examples demonstrating the use of NumPy and Pandas for data analysis:&lt;/h3&gt;
&lt;p&gt;NumPy and Pandas are extensively used in real-world scenarios to tackle various data analysis tasks. Let's explore some practical examples:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h3&gt;Financial Analysis:&lt;/h3&gt;
&lt;p&gt;Financial analysts use NumPy and Pandas to analyze stock market data, perform portfolio optimization, and calculate risk metrics. For example, they might use NumPy to calculate statistical measures like mean, standard deviation, and correlation coefficients, while Pandas is utilized for data manipulation tasks such as merging datasets and handling missing values.&lt;br&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;h3&gt;Sentiment Analysis:&lt;/h3&gt;
&lt;p&gt;In sentiment analysis, which involves analyzing text data to determine sentiment or opinion, NumPy and Pandas are employed to preprocess textual data, extract features, and build machine learning models. For instance, sentiment analysis of customer reviews might involve tokenization, text vectorization using NumPy arrays, and model training with Pandas DataFrame.&lt;br&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;h3&gt;Predictive Modeling:&lt;/h3&gt;
&lt;p&gt;Data scientists use NumPy and Pandas extensively in predictive modeling tasks such as regression, classification, and time series forecasting. They leverage NumPy arrays for feature engineering, model training, and evaluation, while Pandas facilitates data preprocessing, exploratory data analysis, and model validation.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Employ pandas_datareader for fetching real-time financial data directly into Pandas DataFrame for efficient financial analysis.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2&gt;7. Conclusion:&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h3&gt;Recap of the key concepts covered in the guide:&lt;/h3&gt;
&lt;p&gt;In this comprehensive guide, we have covered fundamental and advanced concepts of data analysis using NumPy. We explored NumPy's powerful capabilities for &lt;strong&gt;array manipulation&lt;/strong&gt;, &lt;strong&gt;mathematical operations&lt;/strong&gt;, and &lt;strong&gt;broadcasting&lt;/strong&gt;. Additionally, we delved into practical examples and techniques for working with &lt;strong&gt;multidimensional arrays&lt;/strong&gt;. Moreover, we discussed how Pandas, built on top of NumPy, extends data analysis capabilities with its high-level data structures and manipulation tools.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Regular practice and experimentation are crucial for mastering data analysis with NumPy and Pandas and developing proficiency in real-world projects.
&lt;/span&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;h3&gt;Encouragement for readers to apply their newfound knowledge:&lt;/h3&gt;
&lt;p&gt;Now that you've gained a solid understanding of NumPy and Pandas, it's time to apply your knowledge to &lt;strong&gt;real-world data analysis projects&lt;/strong&gt;. Practice is key to mastering these concepts, so don't hesitate to work on projects that interest you. Experiment with different techniques, explore diverse datasets, and continue learning from online resources and communities. Remember, the more you &lt;strong&gt;practice&lt;/strong&gt;, the more proficient you'll become in data analysis with NumPy and Pandas.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Practice your NumPy and Pandas skills on real-world datasets through Kaggle competitions, open-source projects, or personal projects to solidify your understanding.
&lt;/span&gt;
&lt;/div&gt;
&lt;h2&gt;8. Additional Resources and Further Reading (Optional):&lt;/h2&gt;
&lt;h3&gt;Links to official documentation, tutorials, and online courses:&lt;/h3&gt;
&lt;p&gt;Here are some official resources to deepen your understanding of NumPy and Pandas:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/&quot;&gt;NumPy Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/&quot;&gt;Pandas Official Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/devdocs/user/quickstart.html&quot;&gt;NumPy Quickstart Tutorial&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/getting_started/index.html&quot;&gt;Pandas Getting Started Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.coursera.org/learn/python-data-analysis&quot;&gt;Python Data Analysis Course on Coursera&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;    Explore official documentation, tutorials, and online courses for in-depth learning and stay engaged with online communities for continuous growth and support.
&lt;/span&gt;
&lt;/div&gt;
&lt;h3&gt;Recommended books and resources for mastering data analysis techniques:&lt;/h3&gt;
&lt;p&gt;Here are some recommended books and resources for further exploration:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&quot;Python for Data Analysis&quot;&lt;/em&gt; by Wes McKinney&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&quot;NumPy Cookbook&quot;&lt;/em&gt; by Ivan Idris&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&quot;Pandas Cookbook&quot;&lt;/em&gt; by Theodore Petrou&lt;/li&gt;
&lt;li&gt;&lt;em&gt;&quot;Data Science from Scratch&quot;&lt;/em&gt; by Joel Grus&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;div-faq&quot;&gt;
    &lt;span class=&quot;faq-header&quot;&gt;FAQ:&lt;/span&gt;
    &lt;span class=&quot;faq-body&quot;&gt; &lt;br&gt;   
        &lt;b&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Q. What is NumPy, and why is it important for data analysis?&lt;/span&gt;&lt;/b&gt;b&lt;br&gt;
        A. NumPy, short for Numerical Python, is a Python library used for numerical computing. It provides support for multidimensional arrays and mathematical functions, making it ideal for efficient data manipulation and analysis tasks.&lt;br&gt;
        &lt;b&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Q. What is the difference between NumPy and Pandas?&lt;/span&gt;&lt;/b&gt;&lt;br&gt;
        B. NumPy focuses on numerical computing and provides support for multidimensional arrays, while Pandas is built on top of NumPy and offers high-level data structures and manipulation tools, particularly suited for data analysis tasks with labeled data.&lt;br&gt;
        &lt;b&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Q. Is NumPy used for data analysis?&lt;/span&gt;&lt;/b&gt;&lt;br&gt;
        C. Yes, NumPy is commonly used for data analysis tasks due to its efficient handling of multidimensional arrays and mathematical functions.&lt;br&gt;
        &lt;b&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Q. Should I use NumPy or pandas?&lt;/span&gt;&lt;/b&gt;&lt;br&gt;
        D. NIt depends on your specific needs. If you primarily work with numerical data and require efficient array operations, NumPy is a good choice. If you need to handle labeled data, perform data manipulation tasks, and work with tabular data, pandas is more suitable.&lt;br&gt;
        &lt;b&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Q. Can you use NumPy and pandas together?&lt;/span&gt;&lt;/b&gt;&lt;br&gt;
        D. Yes, NumPy and pandas are often used together in data analysis workflows. While NumPy provides support for numerical operations and arrays, pandas offers high-level data structures like DataFrames and Series, allowing for easier data manipulation and analysis.&lt;br&gt;
    &lt;/span&gt;

&lt;/div&gt;
&lt;p&gt;This comprehensive guide provides a structured approach to mastering data analysis with NumPy and Pandas, covering fundamental concepts, advanced techniques, and real-world applications.&lt;/p&gt;
</description>
<category>Data Science</category>
<guid isPermaLink="true">https://coderlegion.com/202/numpy-tuitorial-data-analysis-for-data-science</guid>
<pubDate>Sun, 24 Mar 2024 09:48:00 +0000</pubDate>
</item>
<item>
<title>NumPy in Python: An Advanced Guide</title>
<link>https://coderlegion.com/191/numpy-in-python-an-advanced-guide</link>
<description>&lt;p&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Table of Contents:&amp;nbsp;&lt;a class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;
&lt;div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;#intro&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Array Iteration&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#num&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;NumPy Operations&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#numpy&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Working with Mathematical Functions&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;NumPy Random Modules&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#arr1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Generating Random Numbers&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#arr2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Setting Seed for Reproducibility&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#index&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;File Input and Output with NumPy&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#fil&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;NumPy and Pandas&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#fil1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Converting between NumPy arrays and Pandas Data Frame&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#file&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Performance Optimization with NumPy&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#file1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Advanced NumPy Topics&lt;/span&gt;&lt;/a&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#file1.1&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Memory Layout and Strides&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#file1.2&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Universal Functions (ufuncs) and Vectorization&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#file1.3&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;NumPy's datetime and timedelta functions&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#con&quot; rel=&quot;nofollow&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Array Iteration&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;The process of iterating across an array in &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/192/numpy-in-python-a-comprehensive-guide-easy?show=192#q192&quot;&gt;NumPy&lt;/a&gt; is called array traversal. Loops and the np.nditer() function are the two main ways to iterate over NumPy arrays.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Iterating with loops&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;NumPy arrays can be iterated over using conventional loops like for loops and &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/184/python-lists?show=184#q184&quot;&gt;list&lt;/a&gt; comprehensions. Nestled loops are usually used to iterate over a multi-dimensional array, navigating through each dimension. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
arr = np.array([[1, 2], [3, 4]])&lt;br&gt;
# Iterating over rows&lt;br&gt;
for row in arr:&lt;br&gt;
&amp;nbsp; &amp;nbsp; print(row)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17562095097812966600&quot; alt=&quot;&quot; width=&quot;390&quot; height=&quot;290&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. Iterating with np.nditer()&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A more effective and versatile method of iterating over NumPy arrays is offered by the np.nditer() function, particularly when working with multi-dimensional arrays or arrays that contain several data types. Regardless of the array's dimensions or structure, it permits continuous iteration across its elements. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
arr = np.array([[1, 2], [3, 4]])&lt;br&gt;
# Iterating with np.nditer()&lt;br&gt;
for x in np.nditer(arr):&lt;br&gt;
&amp;nbsp; &amp;nbsp; print(x)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1488583193388903696&quot; alt=&quot;&quot; width=&quot;390&quot; height=&quot;290&quot;&gt;&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;NumPy Operations&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/user/basics.html&quot;&gt;Numpy&lt;/a&gt; facilitates broadcasting, which enables operations on arrays with various shapes, as well as vectorized operations, which act element-wise on arrays.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Vectorized Operations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;NumPy's vectorized operations make it possible to efficiently operate element-wise on arrays without the use of explicit loops.NumPy uses optimised C implementations to execute computations quickly by applying functions or mathematical operations directly to full arrays. As a result, it is a good choice for numerical workloads in scientific computing, data analysis, and machine learning.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
arr = np.array([1, 2, 3])&lt;br&gt;
result = arr * 2 &amp;nbsp;# Multiply each element by 2&lt;br&gt;
print(result) &amp;nbsp;# Output: [2 4 6]&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Broadcasting&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;NumPy has a powerful method called broadcasting that makes it possible to mix arrays of different shapes for arithmetic operations. It removes the need for manual array copying and reshaping, simplifying code and improving efficiency. It is a key component of NumPy that makes it simple to use and effective for numerical calculations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
arr1 = np.array([[1, 2, 3], [4, 5, 6]])&lt;br&gt;
arr2 = np.array([1, 2, 3])&lt;br&gt;
result = arr1 + arr2&lt;br&gt;
print(result)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3288916113128255398&quot; alt=&quot;&quot; width=&quot;390&quot; height=&quot;290&quot;&gt;&lt;br&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; &lt;span class=&quot;alert-body&quot;&gt;Use NumPy's broadcasting functionality to execute arithmetic operations on arrays with varying dimensions. &lt;/span&gt;&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Working with Mathematical Functions&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;NumPy offers a range of mathematical functions for computing and manipulating arrays.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Mathematical Functions&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;With NumPy, you can compute and manipulate arrays more efficiently due to its extensive mathematical operations. The trigonometric function, the exponential and logarithmic functions, and many other mathematical processes are all covered by these functions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
arr = np.array([0, np.pi/2, np.pi])&lt;br&gt;
# Trigonometric functions&lt;br&gt;
print(np.sin(arr)) &amp;nbsp;# Output: [0.0000000e+00 1.0000000e+00 1.2246468e-16]&lt;br&gt;
# Exponential and logarithmic functions&lt;br&gt;
print(np.exp(arr)) &amp;nbsp;# Output: [ 1. &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;4.81047738 23.14069263]&lt;br&gt;
print(np.log(arr)) &amp;nbsp;# Output: [ &amp;nbsp; &amp;nbsp; &amp;nbsp;-inf 0.45158271 1.14472989] (Note: -inf indicates negative infinity)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Linear Algebra Operations&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;NumPy is an essential tool for applications involving linear algebra in scientific computing, machine learning, and data analysis since it offers strong functions for carrying out these processes. These functions make it possible to work with matrices and vectors efficiently. Some of the operations that they can do include matrix multiplication, eigenvalue decomposition, and solving systems of linear equations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
arr1 = np.array([[1, 2], [3, 4]])&lt;br&gt;
arr2 = np.array([[5, 6], [7, 8]])&lt;br&gt;
# Matrix multiplication&lt;br&gt;
result = np.dot(arr1, arr2)&lt;br&gt;
print(result)&lt;br&gt;
# Eigenvalues and eigenvectors&lt;br&gt;
eigenvalues, eigenvectors = np.linalg.eig(arr1)&lt;br&gt;
print(&quot;Eigenvalues:&quot;, eigenvalues)&lt;br&gt;
print(&quot;Eigenvectors:&quot;, eigenvectors)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;NumPy Random Module&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;For applications like simulation, statistical sampling, and random initialization in machine learning algorithms, the NumPy random module offers functions for creating random integers and random arrays. This module is a flexible tool for creating random data since it provides a large variety of distributions and ways to adjust the unpredictability.&lt;/p&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Generating Random Numbers&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;np.random.rand(): &lt;/strong&gt;The function np.random.rand() produces random numbers between 0 and 1 based on a uniform distribution.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;np.random.randn(): &lt;/strong&gt;Using a conventional normal distribution with a mean of 0 and a standard deviation of 1, np.random.randn() generates random integers.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
# Generate a random number between 0 and 1&lt;br&gt;
random_num = np.random.rand()&lt;br&gt;
print(random_num)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Setting Seed for Reproducibility&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;np.random.seed():&lt;/strong&gt; Establishes the seed for producing random numbers, guaranteeing consistency in outcomes throughout several code executions.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
np.random.seed(42) &amp;nbsp;# Set seed for reproducibility&lt;br&gt;
random_num = np.random.rand()&lt;br&gt;
print(random_num)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;File Input and Output with NumPy&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;NumPy offers useful functions for reading and writing data in binary and text formats to and from files. This functionality is essential for effectively processing data from external files and combining it with NumPy arrays.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;1. Loading and Saving text Files&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The np.loadtxt() function in NumPy loads data into a NumPy array by means of a &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/219/opening-%26-reading-files-handling-in-python?show=219#q219&quot;&gt;text file&lt;/a&gt;. It allows for customisation with respect to data formats, skip headers, and delimiters. Whereas, array data is saved to a text file with formatting choices like headers, footers, and delimiters by using np.savetxt().&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np&lt;br&gt;
# Saving data to a text file&lt;br&gt;
arr = np.array([[1, 2, 3], [4, 5, 6]])&lt;br&gt;
np.savetxt('data.txt', arr)&lt;br&gt;
# Loading data from a text file&lt;br&gt;
loaded_arr = np.loadtxt('data.txt')&lt;br&gt;
print(loaded_arr)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;2. Loading and Saving Binary Files&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The np.load() function in NumPy effectively loads data into a NumPy array while maintaining accuracy and structure from a binary file. On the other hand, NumPy arrays can be saved to binary files using np.save(), which preserves the array's data structure for np.load() loading at a later time.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
# Saving data to a binary file&lt;br&gt;
np.save('data.npy', arr)&lt;br&gt;
# Loading data from a binary file&lt;br&gt;
loaded_arr = np.load('data.npy')&lt;br&gt;
print(loaded_arr)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14815335026538330605&quot; alt=&quot;&quot; width=&quot;390&quot; height=&quot;290&quot;&gt;&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;NumPy and Pandas&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;NumPy is easily integrated with Pandas, a powerful Python data analysis system. It offers a tabular data format, similar to a spreadsheet or SQL table, with labelled rows and columns. Data manipulation operations like filtering, sorting, grouping, and aggregation can be effectively completed with Pandas DataFrame.&lt;/p&gt;
&lt;section&gt;&lt;a id=&quot;fil1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Converting between NumPy arrays and Pandas Data Frame&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Here are few techniques to convert between Pandas Data Frame and NumPy arrays:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
import pandas as pd&lt;br&gt;
# Suppose 'arr' is a NumPy array&lt;br&gt;
arr = np.array([[1, 2, 3], [4, 5, 6]])&lt;br&gt;
# Converting NumPy array to DataFrame&lt;br&gt;
df = pd.DataFrame(arr)&lt;br&gt;
# Converting DataFrame to NumPy array&lt;br&gt;
arr = df.to_numpy()&lt;br&gt;
print(arr)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;file&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Performance Optimization with NumPy&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;NumPy's improved C implementation and effective array-based operations allow it to be significantly faster than native Python lists. NumPy provides &lt;em&gt;faster code execution&lt;/em&gt; and &lt;em&gt;cleaner code&lt;/em&gt; by using vectorized operations and avoiding explicit loops. It is an essential tool for machine learning algorithms, scientific computing activities, and numerical computations because of its &lt;strong&gt;memory layout&lt;/strong&gt; and &lt;strong&gt;ufuncs&lt;/strong&gt;, which further improve efficiency.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;file1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Advanced NumPy Topics&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;section&gt;&lt;a id=&quot;file1.1&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Memory layout and strides&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Understanding the memory architecture and strides of NumPy is &lt;strong&gt;essential &lt;/strong&gt;to comprehending how data is stored and &lt;strong&gt;accessed in arrays&lt;/strong&gt;. The arrangement of elements in memory is known as the memory layout, and the amount of bytes needed to move to the next element along each dimension is known as the stride. Gaining an understanding of these ideas improves memory usage and access patterns, which boosts computation and array operations performance.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;file1.2&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Universal functions (ufuncs) and vectorization&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;NumPy's vectorization and universal functions (ufuncs) are key components that allow for effective &lt;strong&gt;element-wise operations&lt;/strong&gt; on arrays. Without the need for explicit loops, you may perform mathematical operations, trigonometric functions, logical operations, and more to entire arrays using &lt;a rel=&quot;nofollow&quot; href=&quot;https://numpy.org/doc/stable/reference/ufuncs.html&quot;&gt;ufuncs&lt;/a&gt;, which are functions that act element-wise on arrays. &lt;em&gt;Vectorization &lt;/em&gt;is the application of &lt;em&gt;ufuncs to arrays&lt;/em&gt;, which results in faster loop execution times when compared to loops that use scalar operations. NumPy allows for short and effective code for jobs involving numerical computations and data processing by using ufuncs and vectorization.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a id=&quot;file1.3&quot; class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. NumPy's datetime and timedelta functions&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;NumPy has timedelta functions to manipulate time intervals and methods to interact with dates and timings.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import numpy as np &lt;br&gt;
# Creating datetime arrays&lt;br&gt;
dates = np.array(['2022-01-01', '2022-01-02', '2022-01-03'], dtype='datetime64')&lt;br&gt;
print(dates)&lt;br&gt;
# Calculating time differences&lt;br&gt;
diff = np.diff(dates)&lt;br&gt;
print(diff)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9662783552799059689&quot; alt=&quot;&quot; width=&quot;430&quot; height=&quot;330&quot;&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt;&lt;br&gt;Q: What are ufuncs in NumPy?&lt;br&gt;A: Universal functions (ufuncs) in NumPy are functions that operate element-wise on arrays, enabling efficient numerical operations without the need for explicit loops.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;&lt;a class=&quot;custom_anchor&quot;&gt;&lt;/a&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In conclusion, NumPy provides strong tools for effective &lt;strong&gt;mathematical operations&lt;/strong&gt; and &lt;strong&gt;array manipulation&lt;/strong&gt;. Data management is made easier by its support for array iteration, multidimensional slicing, and advanced indexing. NumPy's &lt;strong&gt;optimized efficiency&lt;/strong&gt; and &lt;strong&gt;smooth integration &lt;/strong&gt;with other Python libraries make it indispensable for numerical computing across a range of fields, including scientific computing and machine learning.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;For Refering to Previous Part of the Article:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/192/numpy-in-python-a-comprehensive-guide-easy&quot;&gt;NumPy in Python: A Comprehensive Guide&lt;/a&gt;&lt;/p&gt;
&lt;/section&gt;
</description>
<category>More Libraries</category>
<guid isPermaLink="true">https://coderlegion.com/191/numpy-in-python-an-advanced-guide</guid>
<pubDate>Wed, 13 Mar 2024 11:57:38 +0000</pubDate>
</item>
<item>
<title>NameError: name 'pd' is not defined in Python [Solved]</title>
<link>https://coderlegion.com/156/nameerror-name-pd-is-not-defined-in-python-solved</link>
<description>&lt;h2 id=&quot;introduction-1&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;If you are a newbie to Python and are working with &lt;strong&gt;Pandas&lt;/strong&gt; module, you might get this error &quot;&lt;strong&gt;NameError: name 'pd' is not defined&lt;/strong&gt;&quot;. This error occurs when you are trying to work with &lt;strong&gt;Pandas&lt;/strong&gt; without properly defining the alias as &lt;strong&gt;pd&lt;/strong&gt;. The error is pretty straightforward, but it might leave you puzzled. No worries, in this article we will see what this error means, why it occurs, and how to solve it so let's get started.&lt;/p&gt;
&lt;h2 id=&quot;why-did-this-error-happen-&quot;&gt;Why did this error happen?&lt;/h2&gt;
&lt;p&gt;This error usually occurs while working with the &lt;strong&gt;Pandas&lt;/strong&gt; library in Python. Consider the following code block.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; import pandas # Importing pandas
  df = pd.DataFrame({'Marks': [50, 20, 30],
              'Status': ['Pass', 'Fail', 'Pass']}) # Creating data frame
  print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you run the above code it will give you the below error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=16506121202321903188&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;The error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; suggests that the name &lt;strong&gt;pd&lt;/strong&gt; is not defined which you are using in the code &lt;strong&gt;&lt;code&gt; df = pd.DataFrame({...})&lt;/code&gt;&lt;/strong&gt;. The Python interpreter cannot figure out what exactly &lt;strong&gt;pd&lt;/strong&gt; means. Great, now you know why you are getting this error let's move further.&lt;/p&gt;
&lt;h2 id=&quot;what-is-meant-by-an-alias-&quot;&gt;What is meant by an alias?&lt;/h2&gt;
&lt;p&gt;In the context of programming, an alias refers to an alternative name. It is a common practice for programmers to use aliases instead of actual names. Consider the following code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas # Importing pandas
  df = pandas.DataFrame({'Marks': [50, 20, 30],
              'Status': ['Pass', 'Fail', 'Pass']}) # Creating data frame
  print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above code we are importing &lt;strong&gt;pandas&lt;/strong&gt; and then using it to create a data frame &lt;strong&gt;&lt;code&gt; pandas.DataFrame({...})&lt;/code&gt;&lt;/strong&gt;. Now what if we don't want to use the name &lt;strong&gt;pandas&lt;/strong&gt; instead we want to use a short name that's where aliases come into the picture. Consider the code below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  import pandas as pd # Importing pandas
  df = pd.DataFrame({'Marks': [50, 20, 30],
              'Status': ['Pass', 'Fail', 'Pass']}) # Creating data frame
  print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now in the above code, we have defined an alias name &lt;strong&gt;pd&lt;/strong&gt; as &lt;strong&gt;&lt;code&gt;import pandas as pd&lt;/code&gt;&lt;/strong&gt;, and later we are using &lt;strong&gt;&lt;code&gt;pd.DataFrame({...})&lt;/code&gt;&lt;/strong&gt; instead of &lt;strong&gt;&lt;code&gt;pandas.DataFrame({...})&lt;/code&gt;&lt;/strong&gt;. Now you know what an alias is and why programmers prefer to use an alias instead of simple imports so let's see the causes of this error.&lt;/p&gt;
&lt;h2 id=&quot;what-are-the-causes-of-the-error--1&quot;&gt;What are the causes of the error?&lt;/h2&gt;
&lt;h3 id=&quot;1-module-not-imported&quot;&gt;1. Module not imported&lt;/h3&gt;
&lt;p&gt;If you have not imported the module &lt;strong&gt;&lt;code&gt;import pandas as pd&lt;/code&gt;&lt;/strong&gt; then you are going to get this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt;. Consider the code below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;df = pd.DataFrame({'name': ['ali', 'uzair', 'asim'], 'cgpa': [3.0, 3.5, 3.9]}) # Creating a new data frame
print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above code, you are trying to create a data frame but you have not imported the pandas module so it will result in the following error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17718313030780948174&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;2-alias-not-defined&quot;&gt;2. Alias not defined&lt;/h3&gt;
&lt;p&gt;One reason for getting this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; is the alias is not properly defined. Take a look at the following code block.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas # Importing pandas
  df = pd.DataFrame({'Marks': [50, 20, 30],
              'Status': ['Pass', 'Fail', 'Pass']}) # Creating data frame
  print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After running the above code you will get the following error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17745414560096606305&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;You are getting this error because you have not defined the alias &lt;strong&gt;pd&lt;/strong&gt; that you are using in the code.&lt;/p&gt;
&lt;h3 id=&quot;3-using-local-scope&quot;&gt;3. Using local scope&lt;/h3&gt;
&lt;p&gt;Another reason for getting this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; is you have imported pandas within a local scope that will restrict its use. Consider the following code block.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def create(): # Function for creating a data frame
    import pandas as pd
    pd.DataFrame({'name': ['ali','uzair','asim'], 'marks': [10,20,30]})
   

create() # Calling the create function
pd.DataFrame({'name': ['ali', 'uzair', 'asim'], 'cgpa': [3.0, 3.5, 3.9]}) # Creating a new data frame
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By running the above code you will get the following error.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=8762676568671733460&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this case, you have imported pandas with a proper alias &lt;strong&gt;&lt;code&gt;import pandas as pd&lt;/code&gt;&lt;/strong&gt; but still you are getting this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; the reason is the &lt;strong&gt;local scope&lt;/strong&gt; you have imported pandas inside a function and you are trying to create a data frame outside that function &lt;strong&gt;&lt;code&gt;pd.DataFrame({'name': ['ali', 'uzair', 'asim'], 'cgpa': [3.0, 3.5, 3.9]})&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;div class=&quot;div-red&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;When working with functions be cautious about importing Pandas within a local scope. Importing Pandas locally can restrict its availability&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;how-to-solve-the-error-&quot;&gt;How to solve the error?&lt;/h2&gt;
&lt;h3 id=&quot;1-solution-for-a-module-not-imported&quot;&gt;1. Solution for a module not imported&lt;/h3&gt;
&lt;p&gt;If you haven't imported the panda's module and you are trying to access it then you will get this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt;. To solve it you just need to import the module. Consider the code below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd # Importing the pandas module

df = pd.DataFrame({'name': ['ali', 'uzair', 'asim'], 'cgpa': [3.0, 3.5, 3.9]}) # Creating a new data frame
print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After importing the module &lt;strong&gt;&lt;code&gt;import pandas as pd&lt;/code&gt;&lt;/strong&gt; the error will be removed. Below is the output of the above code.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1601039669656270263&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;You can use &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/164/python-try-except-blocks?show=164#q164&quot; target=&quot;_blank&quot;&gt;try except blocks&lt;/a&gt; for proper error handling.&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Import the module first before using it.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;2-solution-for-alias-not-defined&quot;&gt;2. Solution for alias not defined&lt;/h3&gt;
&lt;p&gt;The error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; clearly says that the name &lt;strong&gt;pd&lt;/strong&gt; is not defined which simply means you are using &lt;strong&gt;pd&lt;/strong&gt; as an alias but haven't defined it which can be simply resolved by defining &lt;strong&gt;pd&lt;/strong&gt; as an alias. Consider the following code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  import pandas as pd # Importing pandas and defining alias as pd
  df = pd.DataFrame({'Marks': [50, 20, 30],
              'Status': ['Pass', 'Fail', 'Pass']}) # Creating a data frame
  print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output of the above code.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2912634916125159969&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Define the alias properly before using it.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;3-solution-for-local-scope&quot;&gt;3. Solution for local scope&lt;/h3&gt;
&lt;p&gt;In the case of local scope try importing pandas as global by doing that you can access it anywhere in your code.  Consider the following code block.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import pandas as pd # Importing pandas in global scope

def create(): # Function for creating a data frame
    pd.DataFrame({'name': ['ali','uzair','asim'], 'marks': [10,20,30]})
   
create() # Calling the create function
df = pd.DataFrame({'name': ['ali', 'uzair', 'asim'], 'cgpa': [3.0, 3.5, 3.9]}) # Creating a new data frame
print(df)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output of the above code.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=15578182080672116880&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-green&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt;
&lt;span class=&quot;alert-body&quot;&gt;Import the module in the global scope to access it anywhere in your code.&lt;/span&gt;
&lt;/div&gt;
&lt;h3 id=&quot;4-solving-the-error-in-jupyter-notebook-or-google-colab&quot;&gt;4. Solving the error in Jupyter Notebook or Google Colab&lt;/h3&gt;
&lt;p&gt;Sometimes you might be working in Jupyter Notebook or Google Colab in this case if you are getting this error &lt;strong&gt;&quot;NameError: name 'pd' is not defined&quot;&lt;/strong&gt; check whether the alias &lt;strong&gt;pd&lt;/strong&gt; is defined in global scope and if not define it and rerun your code.&lt;br&gt;
If the alias is defined properly and you are still getting this error then it might be the following case.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17692736680121642409&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;where the import statement is in a separate cell and you are creating the data frame in a separate cell. In this case, run the previous cell first where you have imported &lt;strong&gt;Pandas&lt;/strong&gt;, and then the cell where you are creating the data frame.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=105449581792552700&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-faq&quot;&gt;
&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt;
&lt;span class=&quot;faq-body&quot;&gt;

Q. What does the error message &quot;NameError: name 'pd' is not defined&quot; mean?&lt;br&gt;  
A. The error suggests that you are using an alias name 'pd' which is not properly defined in your code. 
&lt;br&gt;&lt;br&gt;
Q. How can I resolve the &quot;NameError: name 'pd' is not defined&quot; error?&lt;br&gt; 
A. To resolve it try importing 'import pandas as pd' in a global scope.&lt;br&gt; 
  
&lt;/span&gt;
&lt;/div&gt;
&lt;h2 id=&quot;conclusion-3&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In summary, the error indicates that you are using an alias &lt;strong&gt;pd&lt;/strong&gt; which is not defined in your code. To resolve this problem try to define the alias &lt;strong&gt;&lt;code&gt;import pandas as pd&lt;/code&gt;&lt;/strong&gt; in global scope first before using it. If you are working in Jupyter Notebook or Google Colab you have to define the alias as previous and also try to rerun the cell where you have imported pandas.&lt;/p&gt;
&lt;h2 id=&quot;references-2&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pandas.pydata.org/docs/&quot;&gt;https://pandas.pydata.org/docs/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.w3schools.com/PYTHON/python_scope.asp&quot;&gt;https://www.w3schools.com/PYTHON/python_scope.asp&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://towardsdatascience.com/top-python-libraries-numpy-pandas-8299b567d955&quot;&gt;https://towardsdatascience.com/top-python-libraries-numpy-pandas-8299b567d955&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/156/nameerror-name-pd-is-not-defined-in-python-solved</guid>
<pubDate>Thu, 29 Feb 2024 09:11:50 +0000</pubDate>
</item>
</channel>
</rss>