<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ANUJ SHARMA on Medium]]></title>
        <description><![CDATA[Stories by ANUJ SHARMA on Medium]]></description>
        <link>https://medium.com/@anujajsharma22?source=rss-9d5370b206d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q76vDpw1aMsI_VJDgXkCww.jpeg</url>
            <title>Stories by ANUJ SHARMA on Medium</title>
            <link>https://medium.com/@anujajsharma22?source=rss-9d5370b206d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:18:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anujajsharma22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Snowflake Advanced Data Engineer: Understanding Transactions.]]></title>
            <link>https://medium.com/@anujajsharma22/snowflake-advanced-data-engineer-understanding-transactions-1ca917c0891d?source=rss-9d5370b206d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca917c0891d</guid>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[ANUJ SHARMA]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 15:53:45 GMT</pubDate>
            <atom:updated>2025-07-09T15:59:17.866Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*ochzg4DJguWYGR7YnW_BtA.png" /></figure><h3>🧾 What’s a Transaction?</h3><ul><li>A transaction is a <strong>sequence of SQL statements</strong>.</li><li>It’s either <strong>fully committed</strong> (saved) or <strong>fully rolled back</strong> (undone).</li><li>Snowflake ensures <strong>ACID</strong> compliance: Atomicity, Consistency, Isolation, Durability.</li><li>Can contain <strong>reads (SELECT)</strong> and <strong>writes (INSERT, UPDATE, DELETE)</strong></li></ul><h3>🚫 Nesting Not Allowed</h3><ul><li>No nested transactions — you can’t start one inside another.</li><li>Each transaction stays within a <strong>single session</strong>.</li><li>Multiple sessions <strong>cannot share the same transaction</strong>.</li></ul><h3>💬 Key Terms</h3><ul><li><strong>DDL</strong>: Object creation/modification (e.g., CREATE, ALTER).</li><li><strong>DML</strong>: Data changes (e.g., INSERT, DELETE).</li><li><strong>Query</strong>: SELECT, CALL (CALL can run multiple statements).</li></ul><h3>🟢 Explicit Transactions</h3><ul><li>Start with BEGIN TRANSACTION.</li><li>End with COMMIT or ROLLBACK.</li><li>Extra BEGINs are ignored if one is already active — keep it clean.</li><li>DDL auto-commits — it ends any active transaction before running.</li></ul><h3>🔄 Implicit Transactions</h3><ul><li>Happening quietly behind the scenes — no need to declare them.</li><li>Triggered by DML or query statements depending on AUTOCOMMIT settings.</li></ul><h3>⚙️ AUTOCOMMIT (Default: TRUE)</h3><ul><li><strong>TRUE</strong>: Each statement is auto-committed if successful, rolled back if failed.</li><li><strong>FALSE</strong>: First DML starts a transaction implicitly.</li><li>Changing AUTOCOMMIT (even to the same value) commits the current transaction.</li></ul><p>🚫 Don’t change AUTOCOMMIT inside stored procedures — you’ll get an error!</p><h3>⚠️ Mixing Explicit &amp; Implicit</h3><ul><li>Allowed, but discouraged.</li><li>Example: starting explicitly and ending implicitly (or vice versa) can confuse readers and lead to bugs.</li></ul><h3>💥 Failed Statements in a Transaction</h3><ul><li>Only the <strong>failing statement is rolled back</strong>.</li><li>Other successful statements <strong>remain active</strong>.</li><li>You can still <strong>commit</strong> the transaction if desired.</li></ul><p>👉 Behavior after a failure depends on where you’re running it:</p><ul><li><strong>Stored procedure (no error handling)</strong>: everything rolls back.</li><li><strong>Stored procedure (with error handling)</strong>: earlier success can be committed.</li><li><strong>Snowsight UI</strong>: stops at first error.</li><li><strong>SnowSQL script (-f)</strong>: keeps going after error.</li></ul><h3>🧵 Transactions in Multi-threading</h3><ul><li>Threads sharing the same connection <strong>share the same transaction</strong>.</li><li>One thread’s commit or rollback affects all others.</li><li>✅ Best practice: use <strong>separate connections</strong> or run threads <strong>synchronously</strong>.</li></ul><h3>🧬 Transactions in Stored Procedures</h3><ul><li>Must <strong>start and end inside</strong> the same procedure.</li><li>You <strong>cannot start a transaction outside</strong> and end it inside (or vice versa).</li><li>Each procedure must <strong>own its transaction scope</strong> entirely.</li><li>At the end of a stored procedure, any <strong>active transaction gets rolled back</strong> unless committed earlier.</li></ul><h3>🧵 Multi-threading &amp; Transactions</h3><ul><li>Threads using the <strong>same connection</strong> share the <strong>same transaction</strong>.</li><li>One thread’s <strong>COMMIT or ROLLBACK affects all others</strong> using that connection.</li><li>This can lead to <strong>unexpected behavior</strong> if threads run asynchronously.</li><li>Changing AUTOCOMMIT in one thread also affects other threads on the same connection.</li></ul><p>✅ To avoid chaos:</p><ul><li>Use <strong>separate connections per thread</strong>.</li><li>Run threads <strong>synchronously</strong> to control execution order.</li><li>Watch for <strong>race conditions</strong> (like one thread deleting before another updates).</li></ul><h3>🔐 Stored Procedures &amp; Transaction Scope</h3><h4>📥 Procedure Inside a Transaction</h4><ul><li>If the transaction <strong>starts before</strong> calling the procedure and ends after:</li><li>Procedure follows the outer transaction’s rules.</li><li>If the outer transaction commits, so does everything inside.</li><li>If it rolls back, everything inside rolls back too.</li></ul><p>📌 Don’t start or commit a transaction <strong>inside</strong> the procedure body in this setup.</p><h4>📤 Transaction Inside a Procedure</h4><ul><li>You can write BEGIN TRANSACTION ... COMMIT directly <strong>inside</strong> a procedure.</li><li>Can include <strong>multiple transactions</strong> inside one procedure.</li><li>Just keep each transaction <strong>fully scoped inside</strong> — no crossing boundaries!</li></ul><h3>📦 Scoped Transactions (a.k.a Autonomous Transactions)</h3><ul><li>When a procedure with its own transaction is called <strong>from another active transaction</strong>:</li><li>Each transaction is <strong>independent</strong>.</li><li>One doesn’t affect the other.</li><li>COMMIT inside the procedure is <strong>not undone</strong> by a ROLLBACK outside.</li></ul><p>🧠 Remember:</p><ul><li>Snowflake doesn’t allow <strong>nested transactions</strong>.</li><li>Transactions are <strong>non-overlapping</strong> in terms of content, even if procedures overlap in time.</li></ul><pre>-- Procedure: no transaction inside<br>CREATE OR REPLACE PROCEDURE log_action()<br>  RETURNS STRING<br>  LANGUAGE SQL<br>AS<br>$$<br>  INSERT INTO action_log VALUES (&#39;User action logged&#39;);<br>  RETURN &#39;Done&#39;;<br>$$;<br><br>-- Run with external transaction<br>BEGIN TRANSACTION;<br>  INSERT INTO users VALUES (101, &#39;Ayan&#39;);<br>  CALL log_action();<br>COMMIT;</pre><p>🧠 If you rollback instead of commit, both users and action_log remain untouched.</p><h3>🔁 Transaction Inside a Stored Procedure</h3><p>You can also scope transactions <strong>inside</strong> the procedure itself:</p><pre>v-- Procedure with scoped transaction<br>CREATE OR REPLACE PROCEDURE archive_data()<br>  RETURNS STRING<br>  LANGUAGE SQL<br>AS<br>$$<br>  BEGIN TRANSACTION;<br>    INSERT INTO archive_table SELECT * FROM raw_table WHERE created_at &lt; CURRENT_DATE - 30;<br>    DELETE FROM raw_table WHERE created_at &lt; CURRENT_DATE - 30;<br>  COMMIT;<br><br>  RETURN &#39;Archived&#39;;<br>$$;</pre><p>This runs as a <strong>standalone transaction</strong>, and its COMMIT is final, even if you later ROLLBACK something outside the procedure.</p><h3>🔗 Scoped (Autonomous) Transactions</h3><p>Nested procedures with their own transactions:</p><pre>-- Inner procedure<br>CREATE OR REPLACE PROCEDURE insert_log()<br>  RETURNS STRING<br>  LANGUAGE SQL<br>AS<br>$$<br>  BEGIN TRANSACTION;<br>    INSERT INTO log_table VALUES (&#39;Called inner proc&#39;);<br>  COMMIT;<br>  RETURN &#39;Logged&#39;;<br>$$;<br><br>-- Outer procedure<br>CREATE OR REPLACE PROCEDURE outer_work()<br>  RETURNS STRING<br>  LANGUAGE SQL<br>AS<br>$$<br>  BEGIN TRANSACTION;<br>    INSERT INTO process_table VALUES (&#39;Outer start&#39;);<br>    CALL insert_log();<br>  COMMIT;<br>  RETURN &#39;All done&#39;;<br>$$;</pre><p>📌 insert_log() runs its own transaction, independent of outer_work() Even if you rolled back outer_work(), the log entry would still remain!</p><h3>🔗 Scoped Transactions Across Procedures</h3><ul><li>Each stored procedure can run <strong>its own transaction</strong>, even if called from inside another.</li><li>The <strong>calling procedure’s transaction is separate</strong> from the transaction inside the called procedure.</li><li>Transactions <strong>overlap in time</strong>, but <strong>not in content</strong>.</li></ul><p>🧪 Example:</p><pre>CREATE PROCEDURE p2()<br>...<br>$$<br>  BEGIN TRANSACTION;<br>  statement C;<br>  COMMIT;<br>$$;</pre><pre>CREATE PROCEDURE p1()<br>...<br>$$<br>  BEGIN TRANSACTION;<br>  statement B;<br>  CALL p2();<br>  statement D;<br>  COMMIT;<br>$$;</pre><pre>BEGIN TRANSACTION;<br>statement A;<br>CALL p1();<br>statement E;<br>COMMIT;</pre><p>In this flow:</p><ul><li>Transaction 1: statements A &amp; E (outside procedures)</li><li>Transaction 2: statements B &amp; D (inside p1())</li><li>Transaction 3: statement C (inside p2())</li></ul><p>Each BEGIN/COMMIT pair defines an <strong>autonomous transaction</strong>.</p><h3>⚠️ Improper Scoping = Rollbacks &amp; Errors</h3><p>If BEGIN and COMMIT are not properly paired inside a stored procedure, Snowflake rolls back the transaction and throws an error.</p><p>🧪 Example:</p><pre>CREATE OR REPLACE PROCEDURE outer_sp1()<br>...<br>AS<br>$$<br>  INSERT &#39;osp1_alpha&#39;;<br>  BEGIN WORK;<br>  INSERT &#39;osp1_beta&#39;;<br>  CALL inner_sp2();      -- Problem begins here!<br>  INSERT &#39;osp1_delta&#39;;<br>  COMMIT WORK;<br>  INSERT &#39;osp1_omega&#39;;<br>$$;</pre><pre>CREATE OR REPLACE PROCEDURE inner_sp2()<br>...<br>AS<br>$$<br>  BEGIN WORK;<br>  INSERT &#39;isp2&#39;;<br>  -- Missing COMMIT<br>$$;</pre><pre>CALL outer_sp1();</pre><p>🚨 Outcome:</p><ul><li>isp2 never committed → triggers rollback.</li><li>Error bubbles up → outer procedure outer_sp1() also fails.</li><li>Only &#39;osp1_alpha&#39; is inserted.</li></ul><h3>🧨 Danger of Implicit Transactions with AUTOCOMMIT = FALSE</h3><p>If you forget to commit inside a stored procedure that begins a transaction implicitly, it’s rolled back at the end.</p><p>🧪 Risky Example:</p><pre>ALTER SESSION SET AUTOCOMMIT = FALSE;</pre><pre>CALL p1(); -- p1 contains DML but no COMMIT<br>COMMIT;   -- doesn’t apply to the uncommitted p1 content</pre><p>🧪 Safer Fix #1:</p><pre>ALTER SESSION SET AUTOCOMMIT = FALSE;</pre><pre>BEGIN TRANSACTION;<br>CALL p1();<br>COMMIT WORK;</pre><p>🧪 Safer Fix #2:</p><pre>CREATE PROCEDURE p1() ...<br>$$<br>  BEGIN TRANSACTION;<br>  INSERT INTO parent_table ...;<br>  INSERT INTO child_table ...;<br>  COMMIT WORK;<br>$$;</pre><p>📌 Always make sure:</p><ul><li>BEGIN and COMMIT are balanced.</li><li>Each procedure handles its own transaction scope cleanly.</li><li>Don’t leave active transactions hanging — Snowflake will roll them back automatically.</li></ul><h3>🔐 Isolation Level: READ COMMITTED</h3><ul><li>The only supported level in Snowflake.</li><li>Each statement sees <strong>only committed data</strong> at its start.</li><li>It never sees uncommitted changes from other transactions.</li><li>But it <em>does</em> see uncommitted changes <strong>within its own transaction</strong>.</li></ul><h3>🔒 Locking Behavior</h3><ul><li>Transactions acquire locks on resources like tables.</li><li>Locks are released on COMMIT or ROLLBACK.</li><li>DML statements like UPDATE, DELETE, and MERGE <strong>block each other</strong>.</li><li>INSERT and COPY usually don’t block others—they work on new partitions.</li></ul><p>⚠️ Avoid running DDL (like ALTER TABLE) while INSERT or COPY is active on the same object—it can cause weird inconsistencies.</p><h3>⏳ Lock Timeout Parameters</h3><ul><li>To avoid indefinite waits, use timeouts:</li></ul><pre>ALTER SESSION SET LOCK_TIMEOUT = 7200;  -- 2 hours<br>ALTER SESSION SET HYBRID_TABLE_LOCK_TIMEOUT = 600;  -- 10 minutes</pre><p>🧠 Tip: 0 means “fail fast” if the lock isn’t instantly available.</p><h3>🕸️ Deadlocks</h3><ul><li>Happen when two transactions wait on each other’s locked resources.</li><li>Snowflake picks one as the victim → rolls back just that statement.</li><li>Transaction stays alive — you must commit or roll back manually.</li></ul><p>🧘 SELECT queries don’t cause deadlocks (they’re read-only), but INSERT, UPDATE, DELETE on hybrid tables can.</p><h3>🛠️ Monitoring Transactions &amp; Locks</h3><p>Use these built-in tools:</p><ul><li>SHOW TRANSACTIONS</li><li>SHOW LOCKS</li><li>DESCRIBE TRANSACTION</li><li>LOCK_WAIT_HISTORY view</li><li>Context functions: CURRENT_TRANSACTION, LAST_TRANSACTION, etc.</li></ul><p>📌 Abort stuck transactions:</p><pre>SELECT SYSTEM$ABORT_TRANSACTION(&#39;my_transaction_id&#39;);</pre><h3>⚠️ Auto-Aborts in Detached Sessions</h3><p>Snowflake will automatically roll back:</p><ul><li>If a blocking transaction is idle for <strong>5 mins</strong></li><li>If any transaction is idle for <strong>4 hours</strong></li><li>If working on hybrid tables and idle for <strong>5 mins</strong>, even if not blocking</li></ul><h3>🔒 Why Transactions Get Blocked</h3><ul><li>When two transactions modify the <strong>same resource</strong>, the second one waits.</li><li>Blocked transaction = waiting for a lock.</li><li>Blocking transaction = holds the lock (e.g. on a row or table).</li></ul><h3>🔍 Use LOCK_WAIT_HISTORY View</h3><ul><li>Shows:</li><li>Who’s blocked</li><li>What resource is involved</li><li>Which query is holding the lock</li><li>Time when lock was requested and acquired</li></ul><p><strong>Key columns</strong>:</p><ul><li>transaction_id → who’s waiting</li><li>blocker_queries → JSON with query ID and blocking transaction</li></ul><h3>📌 Example Scenario</h3><p><strong>Transaction B</strong> is blocked:</p><ul><li>Requested lock at time T1</li><li>Blocked by <strong>Transaction A</strong>, specifically Query 2</li><li>Later queries in A may also hold locks — check them all</li></ul><h3>🕰️ Find Long-Blocked Queries (Past 24 Hours)</h3><pre>SELECT query_id, query_text, start_time, session_id, execution_status,<br>       total_elapsed_time, compilation_time, execution_time, transaction_blocked_time<br>FROM snowflake.account_usage.query_history<br>WHERE start_time &gt;= dateadd(&#39;hours&#39;, -24, current_timestamp())<br>  AND transaction_blocked_time &gt; 0<br>ORDER BY transaction_blocked_time DESC;</pre><p>Use the high transaction_blocked_time values to locate affected queries.</p><h3>🕵️ Investigate Blocker Transactions</h3><pre>SELECT object_name, lock_type, transaction_id, blocker_queries<br>FROM snowflake.account_usage.lock_wait_history<br>WHERE query_id = &#39;&lt;query_id&gt;&#39;;</pre><p>Then for each blocker:</p><pre>SELECT query_id, query_text, start_time, session_id, execution_status,<br>       total_elapsed_time, compilation_time, execution_time<br>FROM snowflake.account_usage.query_history<br>WHERE transaction_id = &#39;&lt;transaction_id&gt;&#39;;</pre><p>Focus on DML statements that might’ve held the lock.</p><h3>🧮 Monitor Active Transactions</h3><pre>SHOW TRANSACTIONS;<br>SELECT CURRENT_TRANSACTION();<br>DESCRIBE TRANSACTION &lt;transaction_id&gt;;</pre><p>Gives you the session, start time, status, and ID.</p><h3>🔄 Transaction Visibility in Hybrid Tables</h3><ul><li>Locks shown <strong>only if</strong> blocking or blocked</li><li>Must be blocked <strong>&gt;5 seconds</strong> to be listed</li><li>Results persist <strong>≤15 seconds</strong> after release</li><li>Lock type: ROW</li><li>Object name: Row</li><li>Schema info: NULL</li><li>Multiple rows if multiple transactions blocked on same row</li></ul><h3>🧘 Example Check with LOCK_WAIT_HISTORY</h3><pre>SELECT query_id, object_name, transaction_id, blocker_queries<br>FROM SNOWFLAKE.ACCOUNT_USAGE.LOCK_WAIT_HISTORY<br>WHERE requested_at &gt;= DATEADD(&#39;hours&#39;, -48, CURRENT_TIMESTAMP())<br>LIMIT 1;</pre><p>Look inside blocker_queries JSON to track down the blocking query and transaction ID.</p><p>Memorable summary of <strong>best practices for transactions in Snowflake</strong>🧠💡</p><h3>🧬 Transaction Design</h3><ul><li>Group <strong>related statements</strong> together — they should succeed or fail as one.</li><li>Avoid mixing unrelated logic just for convenience.</li><li>Rollbacks affect the <strong>whole transaction</strong>, not just the failed statement.</li></ul><h3>🚀 Performance Tips</h3><ul><li>Bigger transactions = fewer commits = better performance (on standard tables).</li><li>Example: inserting 10 rows at once is cheaper than 10 single-row inserts.</li><li>But too-large transactions can reduce parallelism and increase risk of deadlocks.</li></ul><h3>⚠️ Deadlock Awareness</h3><ul><li>Larger transactions can lock more resources.</li><li>Locked resources delay other queries.</li><li>Avoid bundling unrelated actions just to optimize throughput.</li></ul><h3>🧊 Hybrid Table Considerations</h3><ul><li>Small AUTOCOMMIT DMLs (under 5 sec or 1 MB) run much faster.</li><li>AUTOCOMMIT TRUE is recommended — it minimizes rollback surprises.</li><li>Prefer BEGIN TRANSACTION for explicit control, not changing AUTOCOMMIT.</li></ul><h3>📘 Readability &amp; Reliability</h3><ul><li>Use one BEGIN TRANSACTION per block—avoid stacking BEGINs.</li><li>Makes it easier to match your COMMIT or ROLLBACK.</li><li>Clear transaction boundaries = clean audit trail and easier debugging.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca917c0891d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About Me]]></title>
            <link>https://medium.com/@anujajsharma22/about-me-c8388f27cc23?source=rss-9d5370b206d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8388f27cc23</guid>
            <category><![CDATA[personal-growth]]></category>
            <dc:creator><![CDATA[ANUJ SHARMA]]></dc:creator>
            <pubDate>Sun, 16 Oct 2022 11:58:45 GMT</pubDate>
            <atom:updated>2024-01-18T13:31:03.916Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>PROJECTS UNDERTAKEN:</strong></p><p><strong>● DP-203 Microsoft Certified Associate Data Engineer.</strong></p><p><strong>● SnowPro Core Data Engineer Certification.</strong></p><p>Worked on a Data Engineering project where half of the data pipeline was already created on AWS but the client wanted to switch to the Azure. I worked mostly on redshift stored procedure in this project on AWS and T-SQL in Azure.</p><p>In my next projects, I worked on snowflake. I created two projects from scratch. Let’s say P1.</p><p>● <strong>Medium article on advanced pandas: </strong><a href="https://medium.com/@anujajsharma22/pandas-for-data-analysts-f376dd10812d"><strong>https://medium.com/@anujajsharma22/pandas-for-data-analysts-f376dd10812d</strong></a></p><p>● <strong>Lead many projects in NWN but cannot write them here due to confidentiality [Statistics, Python, Geopandas) [NWN}</strong></p><p>● <strong>Covid-19 effect on India and Italy: </strong>kaggle.com/devanuj/corona-virus-till-11-march-outbreak-india-italy <strong>[Personal]</strong></p><p>● <strong>Predict automobile prices using various techniques: </strong><a href="https://github.com/ajsharma22/futureAutomobilePredictor">https://github.com/ajsharma22/futureAutomobilePredictor</a> <strong>[Personal]</strong></p><p>● <strong>Correlation Analysis: Rewarded “Dazzle” for this, </strong>checked if present metrics are true representatives of performance. <strong>[Wipro/Alight]</strong></p><p>● <strong>Automated GP System (Excel): </strong>Saved 95% time of calculating the daily gross profit of more than 70 Advertiser’s accounts. <strong>[Affle]</strong></p><p>● <strong>Automated Fraud analysis (Excel): </strong>Saved 95% time of checking the anomaly in data of users. <strong>[Affle]</strong></p><p>● <strong>Increased the profit of an Advertiser’s Account by doing Analysis on 6 months of data. [Affle]</strong></p><p>● <strong>Machine Learning Project </strong>of recognizing hand-written digits. <strong>[College]</strong></p><p><strong>Eventas (</strong>Android application for event organizing) — (<strong>Cofounder</strong>)</p><p><strong>HOBBIES AND OTHER INTEREST:</strong></p><p>● <strong>Amateur Boxer in SBC</strong> <strong>[2014–2018]</strong></p><p>● <strong>Wrestling and Kabaddi [2012–2014]</strong></p><p>● <strong>Reading Classical Novels [Present]</strong></p><p>● <strong>Martial Arts (National level Runner up) [School]</strong></p><p>● <strong>Volunteering for NGOs </strong>(Sewa Bharti and Youth Alliance)<strong> [Present]</strong></p><p><strong>COURSES:</strong></p><p>● <strong>Learning How to Learn: </strong>Powerful mental tools to help you master tough subjects — By Dr. BarBara Oakley: Audited</p><p>● <strong>What is Data Science? — </strong>Alex Aklson — IBM (Data Mining and Regression)</p><p>● <strong>Open Source tools for Data Science-</strong> Polong Lin, Data Scientist, IBM (IBM cognitive lab and Watson studio) and Notebooks</p><p>● <strong>Data Science Methodology- </strong>Alex Aklson — IBM (Data analysis pipeline)</p><p>● <strong>Python for Data Science- </strong>Joseph Santarcangelo — IBM (Project fake album cover)</p><p>● <strong>Databases and SQL for Data Science- </strong>Rav Ahuja — IBM (Advance SQL, using python)</p><p>● <strong>Data Analysis with Python- </strong>Joseph Santarcangelo — IBM (Data Wrangling, Model Development and Evaluation)</p><p>● <strong>Data Visualization with Python </strong>— Alex Aklson — IBM (Advanced Visualizations and Geospatial Data)</p><p>● <strong>Introduction to Psychology: </strong>cognitive abilities it supports like memory, learning, attention, perception and consciousness — By Steeve Joordens.:</p><p>● <strong>Mastering Data Analysis in Excel</strong>: by Duke University</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8388f27cc23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas for Data Analysts]]></title>
            <link>https://medium.com/@anujajsharma22/pandas-for-data-analysts-f376dd10812d?source=rss-9d5370b206d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f376dd10812d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[ANUJ SHARMA]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 08:36:13 GMT</pubDate>
            <atom:updated>2022-12-07T16:59:05.787Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have decided to face the wrath of Dirty data, want to wrestle with unclean data and you show no mercy to outliers as well. Then, you have landed on correct spot.</p><p>Here, I will use examples mostly from the official documentation or from highly upvoted stack overflow answers.</p><p>Let’s jump in.</p><h3><strong>Pandas</strong></h3><p>It’s a python library to perform data manipulation task with high performance.</p><figure><img alt="Not this panda!!!" src="https://cdn-images-1.medium.com/max/1024/0*6Rai9TV437W9v__G" /><figcaption>Photo by <a href="https://unsplash.com/@chriscurry92?utm_source=medium&amp;utm_medium=referral">Chris Curry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s start with conditions:</p><h3><strong>If-else in pandas:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*xz4J7EuRVyIO0NUfD7D0TA.png" /><figcaption>Creating a data frame.</figcaption></figure><p>Now, let’s perform some operations on it:</p><p>if A≥5 then on BBB column changes to -1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*ZyWlQWJ2zIIDocU5KW82pw.png" /><figcaption>when we want to put a constant value.</figcaption></figure><p>Above approach is what most people would choose, but in that approach we have to write more code and we don’t handle else by default.</p><p>We should below approach if there are more than 2 values we have to fill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*mw9fxS1_nLltyDtqqCv7ag.png" /></figure><p>Similarly, for multiple conditions, we can use np.select.</p><p>If we have to perform OR operation in pandas then, use pipe sign (|), similarly, we can use &amp; for AND operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*mupJMB8LcdHqNLn-UnDWWw.png" /></figure><h3><strong>2. Selection:</strong></h3><p>There are 2 explicit slicing methods, optional( name slicing):</p><ol><li>.loc: when there is slicing based on conditions, or labels</li><li>.iloc: when there is slicing based on integer index.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*aRG2Bz4xgONKnsQEt2oEDA.png" /></figure><p>Optional:</p><p>If index are names then we can also use them for slicing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*i3TMZTPYI31X-ZycVMI3PQ.png" /></figure><p>We should not use index based selection until absolute necessary, because if indexes are not sequential then it will generate wrong outputs. Instead, we should use condition based slicing as shown in above sections.</p><p>OR, we should use reset_index(drop=True), before using it.</p><blockquote><strong>df.reset_index(drop=True)</strong></blockquote><p>This command will reset_index to default 0,1,2,… and will not create a new column.</p><h3><strong>isin( [ ] ):</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*hE0DlGg8YSOHU2JGHZrvsw.png" /></figure><p>df[‘column’].isin([ ]) is a really helpful function, if we have multiple values from which we want to check, then isin() is certainly a savior.</p><h3><strong>~ Tilt operator:</strong></h3><p>In pandas if we want to use <strong><em>“not ”</em></strong>operator then we use this sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*8a6Ink6eN3ClMwf4TIXi3w.png" /></figure><pre>df.loc[~(df[&#39;AAA&#39;]==5),:]</pre><h3><strong>3. Advanced groupby :</strong></h3><p>If you know some pandas then you must be aware about this. Few people know about it’s full potential or use it in wrong way.</p><h4>a. <strong>idmax(), idmin():</strong></h4><p>Let’s say in below dataframe, I want to get minimum of “BBB” in every “AAA”.</p><p>There are many ways of achieving this, but do you know about <strong><em>idxmin()</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*wxhyJJNFkjBElNroVvxEIg.png" /></figure><blockquote>Below first we groupby “AAA” and then select “BBB”, after that we get the indexes of minimum values and use those in our selection function loc. Similarly, you can use idmax() function as well.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*rL6rNdeKARRjCXFSsPiNnA.png" /></figure><h4><strong>b. Groupby aggregate:</strong></h4><p>If we want to compute multiple arithmetic operation on multiple columns and also wants to rename the output at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*TSU3qLQuUDGhRHTOGDzCJQ.png" /></figure><p>A special aggfunc we must know about is “<strong>nunique</strong>”. It counts the unique occurrence of values.</p><p>Another deadly missile in our arsenal, rank function, is solution to nothing but our age old nemesis “<em>How to rank values?</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*-iEtpZ48TAT580NmWk2mDg.png" /><figcaption>Have a look at column name first_rank. To perform this operation by any other method, we will have to perform sorting.</figcaption></figure><p>Similarly, if we want to get first 5, or last 5, smallest or largest values, we can use nsmallest / nlargest function.</p><blockquote>In groupby, I also want to cover the pivot table, it is quite helpful in column transformation and groupby in excel style.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*d7okp0uH-6DZJ2DlWyFplw.png" /><figcaption>we are going to perform operation on above dataframe.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*1HHzWDRtWkDlQrHqGN6FkA.png" /><figcaption>Groupby on A and C for columns D and E for arithmetical operations of min, max, and mean.</figcaption></figure><p>pivot_table is different from pivot. pivot is used to only reshape the dataframe, while pivot_table can do both reshaping and aggregating.</p><p>When you use above groupby method, dataframe’s row and columns are multi-indexed. To solve it, simplest method is:</p><pre>df.reset_index(inplace=True)<br>df.columns = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;] # hard code<br>df.columns =[x[0] if x[1]==&#39;&#39; else x[1] for x in df.columns]</pre><h3><strong>Difference between Join, Merge, and Concat:</strong></h3><p>A very high level difference is that merge() is used to combine two (or more) dataframes on the basis of values of common columns (indices can also be used, use left_index=True and/or right_index=True), and concat() is used to append one (or more) dataframes one below the other (or sideways, depending on whether the axis option is set to 0 or 1).</p><p>join() is used to merge 2 dataframes on the basis of the index; instead of using merge() with the option left_index=True we can use join().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WASOITPYM0j7FurE8tjupQ.png" /><figcaption>merged on the basis of values in column “Key”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*rjC3ZvwhxjT-0vDvZa0ttA.png" /><figcaption>concat just append the dataframes</figcaption></figure><p>Join is simple merge on the basis of index.</p><h3><strong>Using Lambda unnecessarily:</strong></h3><p>Many people use lambda even when it is not required, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZkspiJVbv9lK9AjSby2Cg.png" /><figcaption>both last line generate same output,</figcaption></figure><h3>Vectorization in string operations:</h3><p>Instead of using inbuilt python function to manipulate strings, we should always use vectorized functions of pandas.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XKLOwPjlckummoLw41mwA.png" /></figure><p>Above method is slow, inconvenient and most importantly boring.</p><p>What can be fast like flash, efficient, and super interesting other than pandas inbuilt vectorized string functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rrDvmBrw4Inl8t59SdeDg.png" /><figcaption>It handles None values as well by keeping them as None</figcaption></figure><p>There are a lots of string and regular expression vectorized functions.</p><p>len() lower() translate() islower() ljust() upper() startswith() isupper() rjust() find() endswith() isnumeric() center() rfind() isalnum() isdecimal() zfill() index() isalpha() split() strip() rindex() isdigit() rsplit() rstrip() capitalize() isspace() partition() lstrip() swapcase() istitle() rpartition()</p><p><strong>And for regular expressions:</strong></p><p>Method Description</p><p>match() Call re.match() on each element, returning a boolean.</p><p>extract() Call re.match() on each element, returning matched groups as strings.</p><p>findall() Call re.findall() on each element</p><p>replace() Replace occurrences of pattern with some other string</p><p>contains() Call re.search() on each element, returning a boolean</p><p>count() Count occurrences of pattern</p><p>split() Equivalent to str.split(), but accepts regexps</p><p>rsplit() Equivalent to str.rsplit(), but accepts regexps</p><p>My favorite one is split and its’ argument expand:</p><pre>df[&#39;C&#39;].str.split(&#39;l&#39;, n=1)</pre><p>n means for how many times you want to split on the basis of pattern.</p><p>Thank you everyone!!! for staying till last with me.</p><p>May the Force be with You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f376dd10812d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>