<?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"><channel><title><![CDATA[Arjun's Blog]]></title><description><![CDATA[A personal blog about new learnings, quick notes and general ideas.]]></description><link>https://blog.arjunsingh.com.np</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 22:51:15 GMT</lastBuildDate><atom:link href="https://blog.arjunsingh.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Pandas: Import and Export]]></title><description><![CDATA[Pandas CSV
Work with CSV files, read and write like a boss.
Example 1: Read a CSV file.
df = pd.read_csv('file.csv')

Example 2: Write a DataFrame to CSV.
df.to_csv('output.csv', index=False)

Handle CSVs like a data wizard.

Pandas JSON
Handle JSON ...]]></description><link>https://blog.arjunsingh.com.np/pandas-import-and-export</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/pandas-import-and-export</guid><category><![CDATA[pandas]]></category><category><![CDATA[Python]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[numpy]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[data analysis]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Sat, 08 Feb 2025 06:56:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BiWM-utpVVc/upload/e42013ab7e9dcdb52dada126fb132650.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pandas-csv">Pandas CSV</h2>
<p>Work with CSV files, read and write like a boss.</p>
<p>Example 1: Read a CSV file.</p>
<pre><code class="lang-python">df = pd.read_csv(<span class="hljs-string">'file.csv'</span>)
</code></pre>
<p>Example 2: Write a DataFrame to CSV.</p>
<pre><code class="lang-python">df.to_csv(<span class="hljs-string">'output.csv'</span>, index=<span class="hljs-literal">False</span>)
</code></pre>
<p>Handle CSVs like a data wizard.</p>
<hr />
<h2 id="heading-pandas-json">Pandas JSON</h2>
<p>Handle JSON data with ease.</p>
<p>Example 1: Read JSON.</p>
<pre><code class="lang-python">df = pd.read_json(<span class="hljs-string">'file.json'</span>)
</code></pre>
<p>Example 2: Write JSON.</p>
<pre><code class="lang-python">df.to_json(<span class="hljs-string">'output.json'</span>, orient=<span class="hljs-string">'records'</span>)
</code></pre>
<p>JSON is your gateway to modern data formats.</p>
<hr />
<h2 id="heading-pandas-cleaning-data">Pandas Cleaning Data</h2>
<p>Clean data faster than your roommate avoids doing dishes.</p>
<p>Example 1: Strip whitespace.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Column'</span>] = df[<span class="hljs-string">'Column'</span>].str.strip()
</code></pre>
<p>Example 2: Standardize case.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Column'</span>] = df[<span class="hljs-string">'Column'</span>].str.lower()
</code></pre>
<p>Clean data, clean mind.</p>
<hr />
<h2 id="heading-pandas-missing-values">Pandas Missing Values</h2>
<p>Handle missing values like a pro.</p>
<p>Example 1: Fill missing values.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">'A'</span>: [<span class="hljs-number">1</span>, <span class="hljs-literal">None</span>, <span class="hljs-number">3</span>]})
df.fillna(<span class="hljs-number">0</span>, inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>Example 2: Drop rows with missing data.</p>
<pre><code class="lang-python">df.dropna(inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>Because no one likes a blank space (thanks, Taylor Swift).</p>
<hr />
<h2 id="heading-pandas-handling-wrong-format">Pandas Handling Wrong Format</h2>
<p>Fix your messy data formats.</p>
<p>Example 1: Convert strings to dates.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Date'</span>] = pd.to_datetime(df[<span class="hljs-string">'Date'</span>])
</code></pre>
<p>Example 2: Convert strings to numbers.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Numeric'</span>] = pd.to_numeric(df[<span class="hljs-string">'Numeric'</span>], errors=<span class="hljs-string">'coerce'</span>)
</code></pre>
<p>Wrong format? Not anymore.</p>
<hr />
<h2 id="heading-pandas-handling-wrong-data">Pandas Handling Wrong Data</h2>
<p>Replace invalid values.</p>
<p>Example: Replace placeholders with <code>None</code>.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Column'</span>] = df[<span class="hljs-string">'Column'</span>].replace(<span class="hljs-string">'?'</span>, <span class="hljs-literal">None</span>)
</code></pre>
<p>No more wrong data ruining your day.</p>
<hr />
<h2 id="heading-pandas-get-dummies">Pandas Get Dummies</h2>
<p>Convert categories to indicator variables.</p>
<p>Example: Create dummy variables.</p>
<pre><code class="lang-python">dummies = pd.get_dummies(df[<span class="hljs-string">'Category'</span>])
print(dummies)
</code></pre>
<p>Perfect for machine learning models.</p>
<hr />
<h2 id="heading-pandas-categorical">Pandas Categorical</h2>
<p>Optimize memory usage with categorical data types.</p>
<p>Example: Convert to categorical.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Category'</span>] = df[<span class="hljs-string">'Category'</span>].astype(<span class="hljs-string">'category'</span>)
</code></pre>
<p>Save memory, save the planet.</p>
<hr />
<h2 id="heading-pandas-datetime">Pandas Datetime</h2>
<p>Work with datetime like a pro.</p>
<p>Example 1: Extract the year.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Year'</span>] = pd.to_datetime(df[<span class="hljs-string">'Date'</span>]).dt.year
</code></pre>
<p>Example 2: Extract the month.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Month'</span>] = pd.to_datetime(df[<span class="hljs-string">'Date'</span>]).dt.month
</code></pre>
<p>DateTime makes time manipulation a breeze.</p>
<hr />
<h2 id="heading-pandas-aggregate-functions">Pandas Aggregate Functions</h2>
<p>Summarize data efficiently.</p>
<p>Example: Group by and aggregate.</p>
<pre><code class="lang-python">grouped = df.groupby(<span class="hljs-string">'Category'</span>).agg({<span class="hljs-string">'Value'</span>: <span class="hljs-string">'sum'</span>})
print(grouped)
</code></pre>
<p>Aggregations are the secret sauce to insights.</p>
<hr />
<h2 id="heading-pandas-group-by">Pandas Group By</h2>
<p>Group data for analysis.</p>
<p>Example: Group and calculate mean.</p>
<pre><code class="lang-python">print(df.groupby(<span class="hljs-string">'Category'</span>).mean())
</code></pre>
<p>Group by like a data Jedi.</p>
<hr />
<h2 id="heading-pandas-filtering">Pandas Filtering</h2>
<p>Filter rows based on conditions.</p>
<p>Example: Filter rows.</p>
<pre><code class="lang-python">df[df[<span class="hljs-string">'Value'</span>] &gt; <span class="hljs-number">10</span>]
</code></pre>
<p>Keep what you love, ditch the rest.</p>
<hr />
<h2 id="heading-pandas-sort">Pandas Sort</h2>
<p>Sort data like a pro.</p>
<p>Example 1: Sort rows by a column.</p>
<pre><code class="lang-python">df.sort_values(by=<span class="hljs-string">'Value'</span>, ascending=<span class="hljs-literal">False</span>, inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>Example 2: Sort by index.</p>
<pre><code class="lang-python">df.sort_index(inplace=<span class="hljs-literal">True</span>)
</code></pre>
<p>Sorting is as easy as pie.</p>
<hr />
<h2 id="heading-pandas-correlation">Pandas Correlation</h2>
<p>Check correlations between numerical columns.</p>
<p>Example: Compute correlation.</p>
<pre><code class="lang-python">print(df.corr())
</code></pre>
<p>Correlation = your shortcut to patterns.</p>
<hr />
<h2 id="heading-pandas-plot">Pandas Plot</h2>
<p>Visualize data without leaving Pandas.</p>
<p>Example: Line plot.</p>
<pre><code class="lang-python">df.plot(kind=<span class="hljs-string">'line'</span>)
</code></pre>
<p>Example: Bar plot.</p>
<pre><code class="lang-python">df.plot(kind=<span class="hljs-string">'bar'</span>)
</code></pre>
<p>Pandas plotting is your gateway to quick insights.</p>
<hr />
<h2 id="heading-pandas-histogram">Pandas Histogram</h2>
<p>Understand distributions with histograms.</p>
<p>Example 1: Simple histogram.</p>
<pre><code class="lang-python">df[<span class="hljs-string">'Value'</span>].hist()
</code></pre>
<p>Example 2: Multiple histograms.</p>
<pre><code class="lang-python">df[[<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>]].hist()
</code></pre>
<p>Histograms: because data speaks louder than words.</p>
]]></content:encoded></item><item><title><![CDATA[Pandas: DataFrame Operations]]></title><description><![CDATA[Pandas DataFrame Analysis
View and analyze your data frames with built-in Pandas methods. Stats made simple!
Example 1: Get a quick statistical summary.
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
print(df.describe())

# Output:
#          A ...]]></description><link>https://blog.arjunsingh.com.np/pandas-dataframe-operations</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/pandas-dataframe-operations</guid><category><![CDATA[Python]]></category><category><![CDATA[pandas]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[numpy]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Fri, 03 Jan 2025 10:30:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/r8dmu2mchQw/upload/071fb839253f7640d21e780748b89b60.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pandas-dataframe-analysis">Pandas DataFrame Analysis</h2>
<p>View and analyze your data frames with built-in Pandas methods. Stats made simple!</p>
<p>Example 1: Get a quick statistical summary.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">"A"</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-string">"B"</span>: [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]})
print(df.describe())

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#          A    B</span>
<span class="hljs-comment"># count  3.0  3.0</span>
<span class="hljs-comment"># mean   2.0  5.0</span>
<span class="hljs-comment"># std    1.0  1.0</span>
<span class="hljs-comment"># min    1.0  4.0</span>
<span class="hljs-comment"># 25%    1.5  4.5</span>
<span class="hljs-comment"># 50%    2.0  5.0</span>
<span class="hljs-comment"># 75%    2.5  5.5</span>
<span class="hljs-comment"># max    3.0  6.0</span>
</code></pre>
<p>Example 2: Calculate column-wise means.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">"A"</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-string">"B"</span>: [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]})
print(df.mean())

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># A    2.0</span>
<span class="hljs-comment"># B    5.0</span>
<span class="hljs-comment"># dtype: float64</span>
</code></pre>
<p>Example 3: Return the first n rows in a data frame.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)
print(df.head(<span class="hljs-number">3</span>))

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#     Name  Age      City</span>
<span class="hljs-comment"># 0   John   25  New York</span>
<span class="hljs-comment"># 1  Alice   30     Paris</span>
<span class="hljs-comment"># 2    Bob   35    London</span>
</code></pre>
<p>Example 4: Return the last n rows in a data frame.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)
print(df.tail(<span class="hljs-number">3</span>))

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#    Name  Age    City</span>
<span class="hljs-comment"># 2   Bob   35  London</span>
<span class="hljs-comment"># 3  Emma   28  Sydney</span>
<span class="hljs-comment"># 4  Mike   32   Tokyo</span>
</code></pre>
<p>Example 5: Get the data frame information.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)
print(df.info())

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># &lt;class 'pandas.core.frame.DataFrame'&gt;</span>
<span class="hljs-comment"># RangeIndex: 5 entries, 0 to 4</span>
<span class="hljs-comment"># Data columns (total 3 columns):</span>
<span class="hljs-comment">#  #   Column  Non-Null Count  Dtype</span>
<span class="hljs-comment"># ---  ------  --------------  -----</span>
<span class="hljs-comment">#  0   Name    5 non-null      object</span>
<span class="hljs-comment">#  1   Age     5 non-null      int64</span>
<span class="hljs-comment">#  2   City    5 non-null      object</span>
<span class="hljs-comment"># dtypes: int64(1), object(2)</span>
<span class="hljs-comment"># memory usage: 248.0+ bytes</span>
<span class="hljs-comment"># None</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Pro tip: Let Pandas do the math while you grab a coffee.</div>
</div>

<hr />
<h2 id="heading-pandas-dataframe-manipulation">Pandas DataFrame Manipulation</h2>
<p>Add, update, or drop columns and rows with ease.</p>
<p>Example 1: Add and drop columns.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)

df[<span class="hljs-string">"Country"</span>] = [<span class="hljs-string">"United States"</span>, <span class="hljs-string">"France"</span>, <span class="hljs-string">"United Kingdom"</span>, <span class="hljs-string">"Australia"</span>, <span class="hljs-string">"Japan"</span>]
print(df.head(<span class="hljs-number">2</span>))

print(<span class="hljs-string">"================"</span>)

df.drop(<span class="hljs-string">"Age"</span>, axis=<span class="hljs-number">1</span>, inplace=<span class="hljs-literal">True</span>)
<span class="hljs-comment"># To drop multiple: df.drop(["Age", "City"], axis=1, inplace=True)</span>
<span class="hljs-comment"># Using columns: df.drop(columns="Age", inplace=True)</span>
print(df.head(<span class="hljs-number">2</span>))

<span class="hljs-comment">#     Name  Age      City        Country</span>
<span class="hljs-comment"># 0   John   25  New York  United States</span>
<span class="hljs-comment"># 1  Alice   30     Paris         France</span>
<span class="hljs-comment"># ================</span>
<span class="hljs-comment">#     Name      City        Country</span>
<span class="hljs-comment"># 0   John  New York  United States</span>
<span class="hljs-comment"># 1  Alice     Paris         France</span>
</code></pre>
<p>Example 2: Insert and drop rows.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)

df.loc[len(df.index)] = [<span class="hljs-string">"Drake"</span>, <span class="hljs-number">32</span>, <span class="hljs-string">"Bangkok"</span>]
<span class="hljs-comment"># To replace: df.loc[2] = ["Drake", 32, "Bangkok"]</span>
print(df.tail(<span class="hljs-number">2</span>))

print(<span class="hljs-string">"================"</span>)

df.drop(<span class="hljs-number">1</span>, axis=<span class="hljs-number">0</span>, inplace=<span class="hljs-literal">True</span>)
<span class="hljs-comment"># To drop multiple: df.drop([1, 3], axis=0, inplace=True)</span>
<span class="hljs-comment"># Using index: df.drop(index=1, inplace=True)</span>
print(df.head(<span class="hljs-number">2</span>))

<span class="hljs-comment">#     Name  Age     City</span>
<span class="hljs-comment"># 4   Mike   32    Tokyo</span>
<span class="hljs-comment"># 5  Drake   32  Bangkok</span>
<span class="hljs-comment"># ================</span>
<span class="hljs-comment">#    Name  Age      City</span>
<span class="hljs-comment"># 0  John   25  New York</span>
<span class="hljs-comment"># 2   Bob   35    London</span>
</code></pre>
<p>Example 3: Rename column names and indexes.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Emma"</span>, <span class="hljs-string">"Mike"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>, <span class="hljs-number">35</span>, <span class="hljs-number">28</span>, <span class="hljs-number">32</span>],
    <span class="hljs-string">"City"</span>: [<span class="hljs-string">"New York"</span>, <span class="hljs-string">"Paris"</span>, <span class="hljs-string">"London"</span>, <span class="hljs-string">"Sydney"</span>, <span class="hljs-string">"Tokyo"</span>],
}
df = pd.DataFrame(data)

df.rename(columns={<span class="hljs-string">"City"</span>: <span class="hljs-string">"Address"</span>}, inplace=<span class="hljs-literal">True</span>)
<span class="hljs-comment"># Using mapper: df.rename(mapper={"City": "Address"}, axis=1, inplace=True)</span>
print(df.head(<span class="hljs-number">2</span>))

print(<span class="hljs-string">"================"</span>)

df.rename(index={<span class="hljs-number">1</span>: <span class="hljs-number">100</span>}, inplace=<span class="hljs-literal">True</span>)
<span class="hljs-comment"># Using mapper: df.rename(mapper={1: 100}, axis=0, inplace=True)</span>
print(df.head(<span class="hljs-number">2</span>))

<span class="hljs-comment">#     Name  Age   Address</span>
<span class="hljs-comment"># 0   John   25  New York</span>
<span class="hljs-comment"># 1  Alice   30     Paris</span>
<span class="hljs-comment"># ================</span>
<span class="hljs-comment">#       Name  Age   Address</span>
<span class="hljs-comment"># 0     John   25  New York</span>
<span class="hljs-comment"># 100  Alice   30     Paris</span>
</code></pre>
<p>Think of it like playing Tetris but with data.</p>
<hr />
<h2 id="heading-pandas-indexing-and-slicing">Pandas Indexing and Slicing</h2>
<p>Access data with labels or positions—no guessing required.</p>
<p>Example 1: Indexing by column or row.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">'A'</span>: [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>], <span class="hljs-string">'B'</span>: [<span class="hljs-number">30</span>, <span class="hljs-number">40</span>]})
print(df[<span class="hljs-string">'A'</span>])  <span class="hljs-comment"># Access column</span>
print(df.iloc[<span class="hljs-number">0</span>])  <span class="hljs-comment"># Access first row by position</span>
print(df.loc[<span class="hljs-number">0</span>])  <span class="hljs-comment"># Access first row by label</span>
</code></pre>
<p>Example 2: Slice rows and columns.</p>
<pre><code class="lang-python">print(df.iloc[:<span class="hljs-number">1</span>])  <span class="hljs-comment"># First row</span>
print(df[[<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>]])  <span class="hljs-comment"># Selected columns</span>
</code></pre>
<p>Indexing in Pandas is like peeling an onion: layer by layer.</p>
<hr />
<h2 id="heading-pandas-select">Pandas Select</h2>
<p>Filter specific rows or data based on conditions.</p>
<p>Example 1: Simple condition.</p>
<pre><code class="lang-python">print(df[df[<span class="hljs-string">'A'</span>] &gt; <span class="hljs-number">15</span>])
</code></pre>
<p>Example 2: Multiple conditions.</p>
<pre><code class="lang-python">print(df[(df[<span class="hljs-string">'A'</span>] &gt; <span class="hljs-number">10</span>) &amp; (df[<span class="hljs-string">'B'</span>] &lt; <span class="hljs-number">40</span>)])
</code></pre>
<p>It’s like swiping right on the rows you love.</p>
<hr />
<h2 id="heading-pandas-multiindex">Pandas Multiindex</h2>
<p>For when a single index just isn’t enough.</p>
<p>Example: Create and use a MultiIndex.</p>
<pre><code class="lang-python">arrays = [[<span class="hljs-string">'A'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>], [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]]
index = pd.MultiIndex.from_arrays(arrays, names=(<span class="hljs-string">'Letter'</span>, <span class="hljs-string">'Number'</span>))
df = pd.DataFrame({<span class="hljs-string">'Value'</span>: [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>]}, index=index)
print(df)
</code></pre>
<p>MultiIndex is for the overachievers. You know who you are.</p>
<hr />
<h2 id="heading-pandas-reshape">Pandas Reshape</h2>
<p>Reshape your data with <code>melt</code> and <code>pivot</code>.</p>
<p>Example 1: Use <code>melt</code> for long format.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">'ID'</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], <span class="hljs-string">'Value'</span>: [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>]})
melted = pd.melt(df, id_vars=<span class="hljs-string">'ID'</span>)
print(melted
</code></pre>
<p>Example 2: Use <code>pivot</code> for wide format.</p>
<pre><code class="lang-python">pivoted = melted.pivot(index=<span class="hljs-string">'ID'</span>, columns=<span class="hljs-string">'variable'</span>, values=<span class="hljs-string">'value'</span>)
print(pivoted)
</code></pre>
<p>Shape your data like a pro.</p>
<hr />
<h2 id="heading-pandas-duplicate-values">Pandas Duplicate Values</h2>
<p>Find and remove duplicate rows. Because no one likes redundancy.</p>
<p>Example 1: Detect duplicates.</p>
<pre><code class="lang-python">df = pd.DataFrame({<span class="hljs-string">'A'</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>], <span class="hljs-string">'B'</span>: [<span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]})
print(df.duplicated())
</code></pre>
<p>Example 2: Drop duplicates.</p>
<pre><code class="lang-python">df.drop_duplicates(inplace=<span class="hljs-literal">True</span>)
print(df
</code></pre>
<p>Duplicates, begone!</p>
<hr />
<h2 id="heading-pandas-pivot">Pandas Pivot</h2>
<p>Reorganize your data with <code>pivot</code>.</p>
<p>Example: Pivot data.</p>
<pre><code class="lang-python">data = {<span class="hljs-string">'Date'</span>: [<span class="hljs-string">'2024-01-01'</span>, <span class="hljs-string">'2024-01-02'</span>], <span class="hljs-string">'Value'</span>: [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>]}
df = pd.DataFrame(data)
pivoted = df.pivot(index=<span class="hljs-string">'Date'</span>, columns=<span class="hljs-string">'Value'</span>)
print(pivoted)
</code></pre>
<p>Pivots make data feel fancy.</p>
<hr />
<h2 id="heading-pandas-pivot-table">Pandas Pivot Table</h2>
<p>Summarize data with a pivot table.</p>
<p>Example: Create a pivot table.</p>
<pre><code class="lang-python">data = {<span class="hljs-string">'Category'</span>: [<span class="hljs-string">'A'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>], <span class="hljs-string">'Value'</span>: [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>]}
df = pd.DataFrame(data)
pivot_table = df.pivot_table(values=<span class="hljs-string">'Value'</span>, index=<span class="hljs-string">'Category'</span>, aggfunc=<span class="hljs-string">'sum'</span>)
print(pivot_table)
</code></pre>
<p>You’re basically at Excel-level now.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Pandas: Introduction]]></title><description><![CDATA[Getting Started with Pandas
Pandas is a powerful Python library for data manipulation and analysis. Pandas is your gateway to managing data effectively. First step: bring it to your project.
It’s like Excel, but smarter and much less likely to crash ...]]></description><link>https://blog.arjunsingh.com.np/pandas-introduction</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/pandas-introduction</guid><category><![CDATA[Python]]></category><category><![CDATA[pandas]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[numpy]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Mon, 23 Dec 2024 08:51:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Wpnoqo2plFA/upload/3a3dc4ec6ffc6e65181da50ac1d42f42.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-getting-started-with-pandas">Getting Started with Pandas</h2>
<p>Pandas is a powerful Python library for data manipulation and analysis. Pandas is your gateway to managing data effectively. First step: bring it to your project.</p>
<p>It’s like Excel, but smarter and much less likely to crash when you sort something.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
</code></pre>
<hr />
<h2 id="heading-pandas-series">Pandas Series</h2>
<p>A Pandas Series is a one-dimensional labeled array. Think of it as a fancy list with labels (indices). We can access values by their indices.</p>
<p>Example 1: Create a basic Series from the List.</p>
<pre><code class="lang-python">s = pd.Series([<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>])
print(s)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># 0    10</span>
<span class="hljs-comment"># 1    20</span>
<span class="hljs-comment"># 2    30</span>
<span class="hljs-comment"># dtype: int64</span>
</code></pre>
<p>Example 2: Assign custom indices to the elements.</p>
<pre><code class="lang-python">s = pd.Series([<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>], index=[<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>])
print(s)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># a    10</span>
<span class="hljs-comment"># b    20</span>
<span class="hljs-comment"># c    30</span>
<span class="hljs-comment"># dtype: int64</span>
</code></pre>
<p>Example 3: Create a Series from the dictionary.</p>
<pre><code class="lang-python">s = pd.Series({<span class="hljs-string">"bmw"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"honda"</span>: <span class="hljs-number">9</span>, <span class="hljs-string">"suzuki"</span>: <span class="hljs-number">8</span>})
print(s)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># bmw       10</span>
<span class="hljs-comment"># honda      9</span>
<span class="hljs-comment"># suzuki     8</span>
<span class="hljs-comment"># dtype: int64</span>
</code></pre>
<p>Example 4: Create a Series by selecting specific keys from the dictionary.</p>
<pre><code class="lang-python">s = pd.Series({<span class="hljs-string">'bmw'</span>: <span class="hljs-number">10</span>, <span class="hljs-string">'honda'</span>: <span class="hljs-number">9</span>, <span class="hljs-string">'suzuki'</span>: <span class="hljs-number">8</span>}, index=[<span class="hljs-string">'bmw'</span>, <span class="hljs-string">'honda'</span>])
print(s)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># bmw      10</span>
<span class="hljs-comment"># honda     9</span>
<span class="hljs-comment"># dtype: int64</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Fun fact: A Series can hold any data type. Yes, even your favorite memes. In those cases, the <code>dtype</code> will be an <code>object</code>.</div>
</div>

<hr />
<h2 id="heading-pandas-dataframe">Pandas DataFrame</h2>
<p>A DataFrame is a 2D-labeled data structure. Think of it as rows and columns. It’s the bread and butter of Pandas.</p>
<p>Example 1: Create a DataFrame from a dictionary.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#     Name  Age</span>
<span class="hljs-comment"># 0  Alice   25</span>
<span class="hljs-comment"># 1    Bob   30</span>
</code></pre>
<p>Example 2: Create a DataFrame from lists.</p>
<pre><code class="lang-python">data = [[<span class="hljs-number">1</span>, <span class="hljs-string">"John"</span>], [<span class="hljs-number">2</span>, <span class="hljs-string">"Bob"</span>]]
df = pd.DataFrame(data, columns=[<span class="hljs-string">"ID"</span>, <span class="hljs-string">"Name"</span>])
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#    ID  Name</span>
<span class="hljs-comment"># 0   1  John</span>
<span class="hljs-comment"># 1   2   Bob</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Pro tip: DataFrames can hold multiple data types, just like that one junk drawer in your kitchen.</div>
</div>

<hr />
<h2 id="heading-pandas-index">Pandas Index</h2>
<p>The Index is a label array of stored rows and columns. Labels can also be customized.</p>
<p>Example 1: Setting a column as an Index.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
df.set_index(<span class="hljs-string">"Name"</span>, inplace=<span class="hljs-literal">True</span>)
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#        Age</span>
<span class="hljs-comment"># Name</span>
<span class="hljs-comment"># Alice   25</span>
<span class="hljs-comment"># Bob     30</span>
</code></pre>
<p>Example 2: Setting a range as an Index.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data, index=pd.RangeIndex(<span class="hljs-number">100</span>, <span class="hljs-number">102</span>, name=<span class="hljs-string">"Index"</span>))
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#         Name  Age</span>
<span class="hljs-comment"># Index</span>
<span class="hljs-comment"># 100    Alice   25</span>
<span class="hljs-comment"># 101      Bob   30</span>
</code></pre>
<p>Example 3: Renaming an Index.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data, index=pd.RangeIndex(<span class="hljs-number">100</span>, <span class="hljs-number">102</span>, name=<span class="hljs-string">"Index"</span>))
df.rename(index={<span class="hljs-number">101</span>: <span class="hljs-string">"First"</span>}, inplace=<span class="hljs-literal">True</span>)
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#         Name  Age</span>
<span class="hljs-comment"># Index</span>
<span class="hljs-comment"># 100    Alice   25</span>
<span class="hljs-comment"># First    Bob   30</span>
</code></pre>
<p>Example 4: Resetting an Index.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
df.set_index(<span class="hljs-string">"Name"</span>, inplace=<span class="hljs-literal">True</span>)
df.reset_index(inplace=<span class="hljs-literal">True</span>)
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#     Name  Age</span>
<span class="hljs-comment"># 0  Alice   25</span>
<span class="hljs-comment"># 1    Bob   30</span>
</code></pre>
<p>Example 5: Listing Indices.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
print(df.index)
print(df.index.values)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># RangeIndex(start=0, stop=2, step=1)</span>
<span class="hljs-comment"># [0 1]</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Remember, the index is your friend, use it wisely. Few more types of indexes are <code>CategoricalIndex</code>, <code>DatetimeIndex</code>, <code>IntervalIndex</code>, etc.</div>
</div>

<hr />
<h2 id="heading-pandas-array">Pandas Array</h2>
<p>Pandas integrates with NumPy arrays for efficient data storage.</p>
<p>Example 1: Create a pandas array and pandas Series.</p>
<pre><code class="lang-python">arr = pd.array([<span class="hljs-string">"John"</span>, <span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>])
arr_series = pd.Series(arr)
print(arr_series)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># 0     John</span>
<span class="hljs-comment"># 1    Alice</span>
<span class="hljs-comment"># 2      Bob</span>
<span class="hljs-comment"># dtype: string</span>
</code></pre>
<p>Example 2: Convert a column to a NumPy array.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
arr = df[<span class="hljs-string">"Name"</span>].to_numpy()
print(arr)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment"># ['Alice' 'Bob']</span>
</code></pre>
<p>Example 3: Modify data using NumPy.</p>
<pre><code class="lang-python">data = {
    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>],
    <span class="hljs-string">"Age"</span>: [<span class="hljs-number">25</span>, <span class="hljs-number">30</span>],
}
df = pd.DataFrame(data)
arr = df[<span class="hljs-string">"Age"</span>].to_numpy()
df[<span class="hljs-string">"Age"</span>] = arr + <span class="hljs-number">2</span>
print(df)

<span class="hljs-comment"># Output:</span>
<span class="hljs-comment">#     Name  Age</span>
<span class="hljs-comment"># 0  Alice   27</span>
<span class="hljs-comment"># 1    Bob   32</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Fun fact: If you’re a NumPy fan, you’ll feel right at home here.</div>
</div>

<hr />
]]></content:encoded></item><item><title><![CDATA[Revising NumPy: A Cheatsheet]]></title><description><![CDATA[Introduction to NumPy
NumPy is a powerful Python library for numerical computing. It simplifies numerical computations by performing efficient operations on large multidimensional arrays and matrices.
Say goodbye to slow loops and hello to blazing sp...]]></description><link>https://blog.arjunsingh.com.np/numpy-cheatsheet</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/numpy-cheatsheet</guid><category><![CDATA[Python]]></category><category><![CDATA[numpy]]></category><category><![CDATA[pandas]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Mon, 23 Dec 2024 05:40:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/yD5rv8_WzxA/upload/0483a62ea50114bf404e3e9fb33cbbcb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction-to-numpy">Introduction to NumPy</h2>
<p><strong>NumPy</strong> is a powerful Python library for numerical computing. It simplifies numerical computations by performing efficient operations on large multidimensional arrays and matrices.</p>
<p>Say goodbye to slow loops and hello to blazing speed!</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
</code></pre>
<hr />
<h2 id="heading-numpy-array-creation">NumPy Array Creation</h2>
<p>Create arrays using <code>array()</code> or functions such as <code>zeros()</code> and <code>ones()</code>. Think of it as building blocks for your data.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
zeros = np.zeros((<span class="hljs-number">2</span>, <span class="hljs-number">2</span>))
ones = np.ones((<span class="hljs-number">3</span>, <span class="hljs-number">3</span>))
</code></pre>
<hr />
<h2 id="heading-numpy-n-d-array-creation">NumPy N-d Array Creation</h2>
<p>Supports the creation of multi-dimensional arrays. Because 2D is cool, but N-D is cooler.</p>
<pre><code class="lang-python">nd_array = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]])
higher_dim = np.array([[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]], [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>], [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>]]])
</code></pre>
<hr />
<h2 id="heading-numpy-data-types">NumPy Data Types</h2>
<p>Specify or inspect array data types. Useful when you want to avoid unexpected data-type surprises.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1.0</span>, <span class="hljs-number">2.0</span>], dtype=np.float32)
print(arr.dtype)  <span class="hljs-comment"># float32</span>
int_arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], dtype=np.int32)
print(int_arr.dtype)  <span class="hljs-comment"># int32</span>
</code></pre>
<hr />
<h2 id="heading-numpy-array-attributes">NumPy Array Attributes</h2>
<p>Inspect the shape, size, and dimensions of arrays. It’s like peeking under the hood of your array.</p>
<pre><code class="lang-python">arr = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]])
print(arr.shape, arr.size, arr.ndim)  <span class="hljs-comment"># (2, 3), 6, 2</span>
</code></pre>
<hr />
<h2 id="heading-numpy-input-output">NumPy Input Output</h2>
<p>Save and load arrays easily. Think of it as bookmarking your progress.</p>
<pre><code class="lang-python">np.save(<span class="hljs-string">'array.npy'</span>, arr)
loaded = np.load(<span class="hljs-string">'array.npy'</span>)
np.savetxt(<span class="hljs-string">'array.txt'</span>, arr, delimiter=<span class="hljs-string">','</span>)
loaded_txt = np.loadtxt(<span class="hljs-string">'array.txt'</span>, delimiter=<span class="hljs-string">','</span>)
</code></pre>
<hr />
<h2 id="heading-numpy-array-indexing">NumPy Array Indexing</h2>
<p>Access elements by indices. Remember, NumPy arrays are 0-indexed!</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>])
print(arr[<span class="hljs-number">0</span>])  <span class="hljs-comment"># 10</span>
print(arr[<span class="hljs-number">-1</span>])  <span class="hljs-comment"># 30</span>
</code></pre>
<hr />
<h2 id="heading-numpy-array-slicing">NumPy Array Slicing</h2>
<p>Extract sub-arrays using slicing. It’s like cutting a slice of your data pizza.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>])
sub_arr = arr[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]  <span class="hljs-comment"># [2, 3, 4]</span>
every_other = arr[::<span class="hljs-number">2</span>]  <span class="hljs-comment"># [1, 3, 5]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-array-reshaping">NumPy Array Reshaping</h2>
<p>Change the shape without altering data. Rearrange your data like a Rubik’s cube.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>])
reshaped = arr.reshape((<span class="hljs-number">2</span>, <span class="hljs-number">3</span>))  <span class="hljs-comment"># [[1, 2, 3], [4, 5, 6]]</span>
flattened = reshaped.flatten()  <span class="hljs-comment"># [1, 2, 3, 4, 5, 6]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-arithmetic-array-operations">NumPy Arithmetic Array Operations</h2>
<p>Perform element-wise operations. Because who wants to loop through elements manually?</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
result_add = arr + <span class="hljs-number">10</span>  <span class="hljs-comment"># [11, 12, 13]</span>
result_mul = arr * <span class="hljs-number">2</span>  <span class="hljs-comment"># [2, 4, 6]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-array-functions">NumPy Array Functions</h2>
<p>Built-in functions like <code>sum</code> and <code>mean</code> make life easier. They’re like your data’s best friends.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
print(np.sum(arr))  <span class="hljs-comment"># 10</span>
print(np.mean(arr))  <span class="hljs-comment"># 2.5</span>
</code></pre>
<hr />
<h2 id="heading-numpy-comparisonlogical-operations">NumPy Comparison/Logical Operations</h2>
<p>Compare arrays element-wise. Great for filtering data with conditions.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
print(arr &gt; <span class="hljs-number">2</span>)  <span class="hljs-comment"># [False, False, True, True]</span>
print(np.logical_and(arr &gt; <span class="hljs-number">1</span>, arr &lt; <span class="hljs-number">4</span>))  <span class="hljs-comment"># [False, True, True, False]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-math-functions">NumPy Math Functions</h2>
<p>Apply math functions directly. No need for calculators anymore.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>])
print(np.sqrt(arr))  <span class="hljs-comment"># [1. 2. 3.]</span>
print(np.power(arr, <span class="hljs-number">2</span>))  <span class="hljs-comment"># [1 16 81]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-constants">NumPy Constants</h2>
<p>Use predefined constants like <code>pi</code>. For when you don’t want to remember 3.14159.</p>
<pre><code class="lang-python">print(np.pi)  <span class="hljs-comment"># 3.141592653589793</span>
print(np.e)  <span class="hljs-comment"># 2.718281828459045</span>
</code></pre>
<hr />
<h2 id="heading-numpy-statistical-functions">NumPy Statistical Functions</h2>
<p>Compute stats like median, and variance. Perfect for understanding your data’s personality.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
print(np.median(arr))  <span class="hljs-comment"># 2.5</span>
print(np.var(arr))  <span class="hljs-comment"># 1.25</span>
</code></pre>
<hr />
<h2 id="heading-numpy-string-functions">NumPy String Functions</h2>
<p>Operate on strings in arrays. Because even text data needs some love.</p>
<pre><code class="lang-python">names = np.array([<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>])
print(np.char.upper(names))  <span class="hljs-comment"># ['ALICE' 'BOB']</span>
print(np.char.replace(names, <span class="hljs-string">'o'</span>, <span class="hljs-string">'0'</span>))  <span class="hljs-comment"># ['Alice' 'B0b']</span>
</code></pre>
<hr />
<h2 id="heading-numpy-broadcasting">NumPy Broadcasting</h2>
<p>Perform operations on arrays with different shapes. It’s like magic, but with math.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
broadcasted = arr + np.array([<span class="hljs-number">10</span>])  <span class="hljs-comment"># [11, 12, 13]</span>
expanded = arr + np.array([[<span class="hljs-number">10</span>], [<span class="hljs-number">20</span>]])  <span class="hljs-comment"># [[11, 12, 13], [21, 22, 23]]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-matrix-operations">NumPy Matrix Operations</h2>
<p>Matrix multiplication, inversion, etc. Linear algebra geeks, rejoice!</p>
<pre><code class="lang-python">matrix = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]])
print(np.dot(matrix, matrix))  <span class="hljs-comment"># Matrix multiplication</span>
print(np.linalg.inv(matrix))  <span class="hljs-comment"># Matrix inversion</span>
</code></pre>
<hr />
<h2 id="heading-numpy-set-operations">NumPy Set Operations</h2>
<p>Find unique elements and intersections. Useful for deduplication and comparisons.</p>
<pre><code class="lang-python">set1 = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
set2 = np.array([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
print(np.union1d(set1, set2))  <span class="hljs-comment"># [1 2 3 4]</span>
print(np.setdiff1d(set1, set2))  <span class="hljs-comment"># [1]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-vectorization">NumPy Vectorization</h2>
<p>Efficient operations on entire arrays. Skip the loops and embrace speed.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
vectorized = np.vectorize(<span class="hljs-keyword">lambda</span> x: x ** <span class="hljs-number">2</span>)(arr)  <span class="hljs-comment"># [1, 4, 9]</span>
vectorized_add = np.vectorize(<span class="hljs-keyword">lambda</span> x: x + <span class="hljs-number">10</span>)(arr)  <span class="hljs-comment"># [11, 12, 13]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-boolean-indexing">NumPy Boolean Indexing</h2>
<p>Filter elements based on conditions. Let your data speak for itself.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
filtered = arr[arr &gt; <span class="hljs-number">2</span>]  <span class="hljs-comment"># [3, 4]</span>
even = arr[arr % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>]  <span class="hljs-comment"># [2, 4]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-fancy-indexing">NumPy Fancy Indexing</h2>
<p>Access specific elements with lists/arrays. Fancy indeed!</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>])
print(arr[[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>]])  <span class="hljs-comment"># [10, 30]</span>
print(arr[[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>]])  <span class="hljs-comment"># [20, 40]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-random">NumPy Random</h2>
<p>Generate random numbers. Perfect for simulations and shuffling data.</p>
<pre><code class="lang-python">rand_arr = np.random.rand(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>)  <span class="hljs-comment"># Uniform distribution</span>
rand_ints = np.random.randint(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>, (<span class="hljs-number">2</span>, <span class="hljs-number">2</span>))  <span class="hljs-comment"># Random integers</span>
</code></pre>
<hr />
<h2 id="heading-numpy-linear-algebra">NumPy Linear Algebra</h2>
<p>Handle linear algebra operations. Your math professor would approve.</p>
<pre><code class="lang-python">matrix = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]])
print(np.linalg.det(matrix))  <span class="hljs-comment"># Determinant</span>
print(np.linalg.eig(matrix))  <span class="hljs-comment"># Eigenvalues and eigenvectors</span>
</code></pre>
<hr />
<h2 id="heading-numpy-histogram">NumPy Histogram</h2>
<p>Create histograms. Visualize data distribution like a pro.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
hist, bins = np.histogram(arr, bins=<span class="hljs-number">3</span>)
print(hist)  <span class="hljs-comment"># [2 1 4]</span>
print(bins)  <span class="hljs-comment"># [1. 2. 3. 4.]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-interpolation">NumPy Interpolation</h2>
<p>Interpolate data. Filling gaps has never been easier.</p>
<pre><code class="lang-python">x = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
y = [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>]
print(np.interp(<span class="hljs-number">1.5</span>, x, y))  <span class="hljs-comment"># 2.5</span>
print(np.interp([<span class="hljs-number">0.5</span>, <span class="hljs-number">1.5</span>], x, y))  <span class="hljs-comment"># [0.5, 2.5]</span>
</code></pre>
<hr />
<h2 id="heading-numpy-files">NumPy Files</h2>
<p>Read/write text/binary files. Share or save your work effortlessly.</p>
<pre><code class="lang-python">arr = np.array([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]])
np.savetxt(<span class="hljs-string">'data.txt'</span>, arr)
loaded = np.loadtxt(<span class="hljs-string">'data.txt'</span>)
np.save(<span class="hljs-string">'data.npy'</span>, arr)
loaded_bin = np.load(<span class="hljs-string">'data.npy'</span>)
</code></pre>
<hr />
<h2 id="heading-numpy-error-handling">NumPy Error Handling</h2>
<p>Handle errors gracefully. Because no one likes crashing code.</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    result = np.sqrt(<span class="hljs-number">-1</span>)
<span class="hljs-keyword">except</span> FloatingPointError <span class="hljs-keyword">as</span> e:
    print(e)  <span class="hljs-comment"># Domain error</span>
<span class="hljs-keyword">try</span>:
    bad_index = arr[<span class="hljs-number">100</span>]
<span class="hljs-keyword">except</span> IndexError <span class="hljs-keyword">as</span> e:
    print(e)  <span class="hljs-comment"># Index out of bounds</span>
</code></pre>
<hr />
<h2 id="heading-numpy-date-and-time">NumPy Date and Time</h2>
<p>Work with date/time data. Time travel, but for data.</p>
<pre><code class="lang-python">dates = np.arange(<span class="hljs-string">'2023-01-01'</span>, <span class="hljs-string">'2023-01-10'</span>, dtype=<span class="hljs-string">'datetime64[D]'</span>)
duration = np.timedelta64(<span class="hljs-number">1</span>, <span class="hljs-string">'D'</span>)
print(dates + duration)  <span class="hljs-comment"># Increment dates by one day</span>
</code></pre>
<hr />
<h2 id="heading-numpy-data-visualization">NumPy Data Visualization</h2>
<p>Combine with libraries like Matplotlib. Because pictures speak louder than numbers.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
plt.plot(arr)  <span class="hljs-comment"># Line plot</span>
plt.hist(arr)  <span class="hljs-comment"># Histogram</span>
plt.show()
</code></pre>
<hr />
<h2 id="heading-numpy-universal-function">NumPy Universal Function</h2>
<p>Operate element-wise using ufuncs. Fast and functional, just like NumPy.</p>
<pre><code class="lang-python">arr = np.array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
print(np.add(arr, <span class="hljs-number">2</span>))  <span class="hljs-comment"># [3, 4, 5]</span>
print(np.multiply(arr, <span class="hljs-number">2</span>))  <span class="hljs-comment"># [2, 4, 6]</span>
</code></pre>
<hr />
]]></content:encoded></item><item><title><![CDATA[How I Manage Django Settings]]></title><description><![CDATA[Building a Django app is fun until you realize you need different settings for development and production. One day, I accidentally shared my secret keys with the whole internet. Oops.
In this post, I’ll show you how I manage Django settings. It's a l...]]></description><link>https://blog.arjunsingh.com.np/manage-django-settings</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/manage-django-settings</guid><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[django rest framework]]></category><category><![CDATA[production]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Tue, 10 Sep 2024 19:03:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/jpgRztEuaV4/upload/1955b055bd05b62c2b18fad8d993d533.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Building a Django app is fun until you realize you need different settings for development and production. One day, I accidentally shared my secret keys with the whole internet. Oops.</p>
<p>In this post, I’ll show you how I manage Django settings. It's a lifesaver when you have to deal with different environments.</p>
<hr />
<h2 id="heading-why-bother-with-django-settings"><strong>Why Bother with Django Settings?</strong></h2>
<p>Imagine working on your app locally, everything looks perfect. Then you push it to production, and boom! Something breaks. Maybe you left debug mode on, or worse, exposed all your secrets.</p>
<p>Managing settings is like having different outfits for different occasions. You wouldn’t wear pajamas to a job interview, right? Same with Django, your settings should change depending on where you’re running your app.</p>
<hr />
<h2 id="heading-using-environment-variables-keep-your-secrets-hidden"><strong>Using Environment Variables: Keep Your Secrets Hidden</strong></h2>
<p>You don’t want your secret keys, database passwords, or API keys lying around in your code for everyone to see. Trust me, it's not a good look.</p>
<p>I use <code>python-decouple</code> to handle this. It helps me load environment variables and keep my settings clean.</p>
<p>First, install it:</p>
<pre><code class="lang-bash">pip install python-decouple
</code></pre>
<p>Now, in <code>settings.py</code>, grab your environment variables:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>
<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config

SECRET_KEY = config(<span class="hljs-string">'SECRET_KEY'</span>)
DEBUG = config(<span class="hljs-string">'DEBUG'</span>, cast=bool)
</code></pre>
<p>Store the real secrets in a <code>.env</code> file. Don’t forget to add this file to your <code>.gitignore</code>. You don’t want to share your secrets like I did.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># .env</span>
SECRET_KEY=<span class="hljs-string">'supersecretkey'</span>
DEBUG=True
</code></pre>
<p>Congrats! Now, your sensitive data is safe from prying eyes.</p>
<hr />
<h2 id="heading-handling-multiple-environments-because-one-is-never-enough"><strong>Handling Multiple Environments (Because One is Never Enough)</strong></h2>
<p>You probably have different setups for development and production. In development, you might use SQLite. But in production, you need something fancier like PostgreSQL.</p>
<p>Here’s how I handle multiple environments without losing my sanity.</p>
<h4 id="heading-step-1-split-settings"><strong>Step 1: Split Settings</strong></h4>
<p>First, I split my settings into three files:</p>
<ul>
<li><p><code>base.py</code> for shared settings.</p>
</li>
<li><p><code>development.py</code> for local work.</p>
</li>
<li><p><code>production.py</code> for the big leagues (aka production).</p>
</li>
</ul>
<p>It looks something like this:</p>
<pre><code class="lang-bash">/project
    ├── settings/
    │   ├── __init__.py
    │   ├── base.py
    │   ├── development.py
    │   └── production.py
</code></pre>
<h4 id="heading-step-2-common-settings-in-basepy"><strong>Step 2: Common Settings in</strong> <code>base.py</code></h4>
<p>In <code>base.py</code>, I put everything that’s the same for all environments.</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/base.py</span>
<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config

INSTALLED_APPS = [
    <span class="hljs-comment"># Your apps here</span>
]

SECRET_KEY = config(<span class="hljs-string">'SECRET_KEY'</span>)

DATABASES = {
    <span class="hljs-string">'default'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.sqlite3'</span>,
        <span class="hljs-string">'NAME'</span>: config(<span class="hljs-string">'DB_NAME'</span>, default=<span class="hljs-string">'db.sqlite3'</span>),
    }
}
</code></pre>
<h4 id="heading-step-3-custom-settings-for-each-environment"><strong>Step 3: Custom Settings for Each Environment</strong></h4>
<p>In <code>development.py</code>, I set up things like debugging and using SQLite.</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/development.py</span>
<span class="hljs-keyword">from</span> .base <span class="hljs-keyword">import</span> *

DEBUG = <span class="hljs-literal">True</span>

DATABASES = {
    <span class="hljs-string">'default'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.sqlite3'</span>,
        <span class="hljs-string">'NAME'</span>: config(<span class="hljs-string">'DB_NAME'</span>, default=<span class="hljs-string">'db.sqlite3'</span>),
    }
}
</code></pre>
<p>In <code>production.py</code>, I switch to PostgreSQL and turn off debugging. No need to let the world see your errors!</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/production.py</span>
<span class="hljs-keyword">from</span> .base <span class="hljs-keyword">import</span> *

DEBUG = <span class="hljs-literal">False</span>

DATABASES = {
    <span class="hljs-string">'default'</span>: {
        <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.postgresql'</span>,
        <span class="hljs-string">'NAME'</span>: config(<span class="hljs-string">'DB_NAME'</span>),
        <span class="hljs-string">'USER'</span>: config(<span class="hljs-string">'DB_USER'</span>),
        <span class="hljs-string">'PASSWORD'</span>: config(<span class="hljs-string">'DB_PASSWORD'</span>),
    }
}
</code></pre>
<h4 id="heading-step-4-load-the-right-settings-automatically"><strong>Step 4: Load the Right Settings Automatically</strong></h4>
<p>In <code>settings/__init__.py</code>, I decide which settings to use based on an environment variable. Fancy, huh?</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/__init__.py</span>
<span class="hljs-keyword">from</span> decouple <span class="hljs-keyword">import</span> config

ENV = config(<span class="hljs-string">'DJANGO_ENV'</span>, default=<span class="hljs-string">'development'</span>)

<span class="hljs-keyword">if</span> ENV == <span class="hljs-string">'production'</span>:
    <span class="hljs-keyword">from</span> .production <span class="hljs-keyword">import</span> *
<span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">from</span> .development <span class="hljs-keyword">import</span> *
</code></pre>
<p>In your <code>.env</code>, you can set the environment like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># .env</span>
DJANGO_ENV=<span class="hljs-string">'development'</span>  <span class="hljs-comment"># Or 'production'</span>
</code></pre>
<p>Now, when you deploy, Django will use the right settings without any extra effort from you.</p>
<hr />
<h3 id="heading-static-and-media-files-the-pesky-duo"><strong>Static and Media Files: The Pesky Duo</strong></h3>
<p>Managing static and media files in different environments can be annoying. Locally, I just serve them from my app. In production, I need something more serious like AWS S3.</p>
<p>For development:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/development.py</span>
STATIC_URL = <span class="hljs-string">'/static/'</span>
MEDIA_URL = <span class="hljs-string">'/media/'</span>
</code></pre>
<p>For production:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings/production.py</span>
STATIC_URL = <span class="hljs-string">'/static/'</span>
STATIC_ROOT = <span class="hljs-string">'/path/to/static/'</span>

MEDIA_URL = <span class="hljs-string">'/media/'</span>
MEDIA_ROOT = <span class="hljs-string">'/path/to/media/'</span>
</code></pre>
<p>Now, my files work everywhere without me worrying about broken images or missing styles.</p>
<hr />
<h2 id="heading-keep-secrets-out-of-git-seriously"><strong>Keep Secrets Out of Git (Seriously)</strong></h2>
<p>Make sure your <code>.env</code> file is in <code>.gitignore</code>. I learned this the hard way. Once, I committed my secret keys to GitHub, and bots immediately started sniffing around my repo.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># .gitignore</span>
.env
</code></pre>
<p>Don’t be like me. Keep your secrets secret.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[I thought I knew all about Python Generators]]></title><description><![CDATA[Python generators are like magic tricks for handling data. They help you work with large amounts of information without using up all your memory.
If you think you know everything about them, think again! I recently found a cool new way to use generat...]]></description><link>https://blog.arjunsingh.com.np/python-generators</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/python-generators</guid><category><![CDATA[Python]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Wed, 04 Sep 2024 16:13:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/x7hDb7nlz8k/upload/ecc2111764db3c6ab80a653e588c6364.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Python generators are like magic tricks for handling data. They help you work with large amounts of information without using up all your memory.</p>
<p>If you think you know everything about them, think again! I recently found a cool new way to use generators that totally surprised me.</p>
<hr />
<h2 id="heading-what-are-python-generators">What Are Python Generators?</h2>
<p>Think of Python generators as smart vending machines for data. Instead of giving you all the items at once, they hand them out one by one.</p>
<p>You get a snack here, a snack there—one <code>yield</code> at a time.</p>
<p>Here’s a simple example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_up_to</span>(<span class="hljs-params">max</span>):</span>
    count = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> count &lt;= max:
        <span class="hljs-keyword">yield</span> count
        count += <span class="hljs-number">1</span>
</code></pre>
<p>When you use this generator, it’s like having a conveyor belt of numbers:</p>
<pre><code class="lang-python">counter = count_up_to(<span class="hljs-number">5</span>)
<span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> counter:
    print(number)
</code></pre>
<p>And you get:</p>
<pre><code class="lang-bash">1
2
3
4
5
</code></pre>
<p>No need to store all the numbers at once—just a steady stream of digits.</p>
<hr />
<h2 id="heading-what-i-already-knew">What I Already Knew</h2>
<p>Before my recent discovery, I thought I had generators all figured out. I knew how to make them, use them, and even had some tricks up my sleeve. Here’s what I was doing:</p>
<h3 id="heading-simple-generator-function"><strong>Simple Generator Function</strong></h3>
<p>A basic generator function that yields items one by one:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">simple_gen</span>():</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>
</code></pre>
<p>You can use this generator like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> simple_gen():
    print(char)
</code></pre>
<p>And you get:</p>
<pre><code class="lang-bash">a
b
c
</code></pre>
<h3 id="heading-generator-expressions"><strong>Generator Expressions</strong></h3>
<p>I also used generator expressions for creating sequences on the fly:</p>
<pre><code class="lang-python">squares = (x * x <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>))
</code></pre>
<p>You can iterate over this generator like so:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> square <span class="hljs-keyword">in</span> squares:
    print(square)
</code></pre>
<p>And you get:</p>
<pre><code class="lang-bash">0
1
4
9
16
</code></pre>
<h3 id="heading-using-next-with-generators"><strong>Using</strong> <code>next</code> with Generators</h3>
<p>Another cool trick I used was the <code>next</code> function, which lets you manually fetch the next item from a generator. Here’s an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_up_to</span>(<span class="hljs-params">max</span>):</span>
    count = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> count &lt;= max:
        <span class="hljs-keyword">yield</span> count
        count += <span class="hljs-number">1</span>

counter = count_up_to(<span class="hljs-number">3</span>)

print(next(counter))  <span class="hljs-comment"># Outputs: 1</span>
print(next(counter))  <span class="hljs-comment"># Outputs: 2</span>
print(next(counter))  <span class="hljs-comment"># Outputs: 3</span>
print(next(counter))  <span class="hljs-comment"># Raises StopIteration</span>
</code></pre>
<p>With <code>next</code>, you can grab items one at a time, and when the generator is done, it raises a <code>StopIteration</code> exception to let you know.</p>
<p>Generators were my go-to for handling large data. They helped me read big files line by line and deal with large queries without breaking a sweat.</p>
<hr />
<h2 id="heading-what-i-discovered">What I Discovered</h2>
<p>I was pretty surprised when I discovered a new way to use generators that made me feel like I was missing out on a great tool.</p>
<h3 id="heading-nested-generator-function">Nested Generator Function</h3>
<p>Enter <code>yield from</code>—a way to use multiple generators together.</p>
<p>Here’s how it works:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gen1</span>():</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gen2</span>():</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">combined_gen</span>():</span>
    print(<span class="hljs-string">"From First Generator"</span>)
    <span class="hljs-keyword">yield</span> <span class="hljs-keyword">from</span> gen1()

    print(<span class="hljs-string">"From Second Generator"</span>)
    <span class="hljs-keyword">yield</span> <span class="hljs-keyword">from</span> gen2()
</code></pre>
<p>When you use <code>combined_gen()</code>, it’s like getting data from both <code>gen1</code> and <code>gen2</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> combined_gen():
    print(item)
</code></pre>
<p>And you get:</p>
<pre><code class="lang-bash">From First Generator
1
2
3
From Second Generator
a
b
c
</code></pre>
<h3 id="heading-using-next-with-nested-generators"><strong>Using</strong> <code>next</code> with Nested Generators</h3>
<p>You can also use <code>next</code> to step through nested generators:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gen1</span>():</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gen2</span>():</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">combined_gen</span>():</span>
    print(<span class="hljs-string">"From First Generator"</span>)
    <span class="hljs-keyword">yield</span> <span class="hljs-keyword">from</span> gen1()

    print(<span class="hljs-string">"From Second Generator"</span>)
    <span class="hljs-keyword">yield</span> <span class="hljs-keyword">from</span> gen2()

gen = combined_gen()

print(next(gen))  <span class="hljs-comment"># Prints: "From First Generator" &amp; Outputs: 1</span>
print(next(gen))  <span class="hljs-comment"># Outputs: 2</span>
print(next(gen))  <span class="hljs-comment"># Outputs: 3</span>
print(next(gen))  <span class="hljs-comment"># Prints: "From Second Generator" &amp; Outputs: a</span>
print(next(gen))  <span class="hljs-comment"># Outputs: b</span>
print(next(gen))  <span class="hljs-comment"># Outputs: c</span>
print(next(counter))  <span class="hljs-comment"># Raises StopIteration</span>
</code></pre>
<p>In this example, <code>yield from</code> combines data from two generators, and using <code>next</code> lets you step through the output one item at a time.</p>
<p>It’s like having a remote control for your generator's data stream.</p>
<hr />
<h2 id="heading-why-this-matters">Why This Matters</h2>
<p>Finding out about <code>yield from</code> felt like discovering a hidden feature on a tool you already use. It makes your code cleaner and easier to manage, especially when working with multiple data sources.</p>
<p>So, if you think you’ve mastered generators, give <code>yield from</code> a try. It might just make your coding life a lot easier and cooler.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[From Production to Public]]></title><description><![CDATA[So, there I was. My app was up and running in production, ticking along smoothly on AWS.
But what’s the point of having a perfectly tuned app if no one can access it? It was time to take that final step: going public.
This post is all about that last...]]></description><link>https://blog.arjunsingh.com.np/production-to-public</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/production-to-public</guid><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Tue, 27 Aug 2024 03:58:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/JKUTrJ4vK00/upload/1c39ae549b5fdbd9da73bce227e67e20.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So, there I was. My app was up and running in production, ticking along smoothly on AWS.</p>
<p>But what’s the point of having a perfectly tuned app if no one can access it? It was time to take that final step: going public.</p>
<p>This post is all about that last-mile journey—where I took my app from "everything works in production" to "everything is live, stable, and ready for the public." Let me walk you through how I did it.</p>
<hr />
<h2 id="heading-cloudflare-r2-offloading-static-and-media-files">Cloudflare R2: Offloading Static and Media Files</h2>
<p>One of the first things I tackled was moving my static and media files off my EC2 instance and into Cloudflare R2. Managing those files directly on the server was never going to scale well, so I decided to offload them to R2. It's like Cloudflare’s version of S3—perfect for my needs.</p>
<p>I set up the bucket and linked it to my app. It didn’t take long, and before I knew it, my app was serving static and media files from R2 instead of the EC2.</p>
<p>That change alone made my setup feel more polished and took some weight off the server, freeing it up to do the heavy lifting.</p>
<hr />
<h2 id="heading-monitoring-with-prometheus-and-grafana">Monitoring with Prometheus and Grafana</h2>
<p>With the app running smoothly, my next concern was keeping tabs on everything. After all, if something crashes, I want to know about it before my users do. Time to use Prometheus and Grafana.</p>
<p>Prometheus started scraping all kinds of metrics from my Docker containers—everything from CPU and memory usage to request counts. Grafana took all that data and made it pretty with some slick dashboards.</p>
<p>Now I can pull up a real-time view of how the app is performing anytime I want. Plus, I set up some alerts to notify me if anything starts going off the rails.</p>
<p>Of course, that meant I needed secure access to these monitoring tools without exposing them directly to the internet. This is where Tailscale came in handy.</p>
<hr />
<h2 id="heading-setting-up-dns-for-prometheus-and-grafana-with-tailscale">Setting Up DNS for Prometheus and Grafana with Tailscale</h2>
<p>I configured Prometheus and Grafana to run in my private Docker network alongside my other containers. But rather than leaving these services open to the public, I decided to route them through Nginx using Tailscale’s private VPN.</p>
<p>I have already set up Tailscale, which gave me a secure, private IP that could only be accessed within my VPN network. Then, I configured DNS entries in Cloudflare for both Prometheus and Grafana as well, similar to Portainer.</p>
<p>Also, I had to get SSL certificates for new subdomains and set them up in the Nginx config.</p>
<p>The DNS entries pointed to my private Tailscale IP, and from there, Nginx routed the traffic to the appropriate services within the Docker network.</p>
<p>With this setup, I could access <code>prometheus.mydomain.com</code> and <code>grafana.mydomain.com</code> securely through Tailscale, while keeping both services completely invisible to the outside world. All the management and monitoring power, none of the public exposure.</p>
<hr />
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>After getting all that setup, offloading static files, monitoring performance, and securely accessing Prometheus and Grafana through Tailscale, it was time to flip the switch.</p>
<p>And that’s it, the app is now public, live, and working as expected. I’m happy with where it’s at, and I’ve got everything in place to keep it running smoothly.</p>
]]></content:encoded></item><item><title><![CDATA[From Local to Production]]></title><description><![CDATA[Hey there! So, I recently took the plunge and moved my local app to AWS. It’s been quite the adventure, and I thought I'd share the step-by-step process I followed. Let’s dive in!

Setting Up the Domain and SSL
First off, I grabbed a domain—nothing f...]]></description><link>https://blog.arjunsingh.com.np/local-to-production</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/local-to-production</guid><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Tue, 13 Aug 2024 10:32:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/vIQDv6tUHYk/upload/6d5996f40f97aeccf84ee90a4ef7f3c9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there! So, I recently took the plunge and moved my local app to AWS. It’s been quite the adventure, and I thought I'd share the step-by-step process I followed. Let’s dive in!</p>
<hr />
<h2 id="heading-setting-up-the-domain-and-ssl">Setting Up the Domain and SSL</h2>
<p>First off, I grabbed a domain—nothing fancy, just the usual process of buying from a registrar. For this setup, I used Cloudflare to manage the DNS. Here’s how it went down:</p>
<h3 id="heading-pointing-the-domain-to-cloudflare">Pointing the Domain to Cloudflare</h3>
<p>I signed up on Cloudflare, added my domain, and followed their instructions to point my domain to their nameservers. Simple enough, right? Just had to update the nameservers with my domain registrar.</p>
<h3 id="heading-configuring-ssltls">Configuring SSL/TLS</h3>
<p>Next up, I wanted to make sure everything was secure. In Cloudflare, I set the SSL/TLS encryption mode to "Strict". This mode ensures that traffic between Cloudflare and my origin server is encrypted.</p>
<p>I also generated a certificate for my origin server. This certificate would come into play later when I set up Nginx.</p>
<hr />
<h2 id="heading-dockerizing-the-app">Dockerizing the App</h2>
<p>Alright, with the domain and SSL sorted, it was time to Dockerize my app and get things rolling on AWS.</p>
<p>I kicked things off by Dockerizing my app, and that meant writing up a Docker Compose file. Nothing too crazy—just setting up Nginx alongside my app in the same file.</p>
<p>Remember that origin certificate I created earlier in Cloudflare? Well, I mounted that <code>crt</code> and <code>key</code> files in the Nginx container and used it for SSL.</p>
<p>Then, I made sure everything was working by opening my app through Nginx. Success!</p>
<hr />
<h2 id="heading-setting-up-aws">Setting Up AWS</h2>
<p>With Docker set up, it was time to get AWS involved. I launched an EC2 instance, making sure to configure it with the right VPC, subnet, route table, and security groups to allow traffic on ports 22, 80, and 443. I added my PC's SSH key as well.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">I will remove port 22 (SSH) later. Don't want to leave that open for public.</div>
</div>

<p>It was time to put Docker to work for what it was built for. So, I went ahead and installed Docker on my EC2 machine and copied my project over using SCP.</p>
<p>Once that was done, I SSHed into the EC2 instance and started up the container. Simple as that!</p>
<p>I verified everything was set up correctly by opening the public IP of my EC2 in the browser.</p>
<p>Yahhooo! My hobby project was officially live on the internet. But hold up—was I really going to stick with the IP address? Do I have to type out the IP instead of using <code>mydomain.com</code>?</p>
<hr />
<h2 id="heading-final-touches-dns-and-portainer">Final Touches: DNS and Portainer</h2>
<p>With the app running, it was time to polish things off.</p>
<h3 id="heading-configuring-cloudflare-dns">Configuring Cloudflare DNS</h3>
<p>I went back to Cloudflare and added an A Record pointing to my EC2’s public IP. I also added a CNAME Record for the www subdomain. And voilà—my website was live with my own domain!</p>
<p>Thank god I didn't have to use IP anymore.</p>
<h3 id="heading-managing-docker-containers-with-portainer">Managing Docker Containers with Portainer</h3>
<p>To keep an eye on my Docker containers, I went ahead and installed Portainer, hooking it up to the Nginx network.</p>
<p>Then, I tweaked the Nginx config to route traffic to <code>portainer.mydomain.com</code>. I also added WebSocket config in Nginx since I needed to access the container's shell in Portainer, and WebSockets makes that happen.</p>
<p>After that, I jumped back into Cloudflare and added a subdomain for Portainer, pointing it right at the EC2’s public IP.</p>
<p>I checked to make sure Portainer was set up properly, and yep, everything was working smoothly—I could access everything without a hitch. But, there was a catch: everything was out there on the public internet.</p>
<p>Portainer’s own docs even mention that its default authentication isn’t exactly recommended for security.</p>
<hr />
<h2 id="heading-setting-up-tailscale-vpn">Setting Up Tailscale VPN</h2>
<p>After setting up Portainer for managing my Docker containers, I realized I didn’t want it to be accessible over the public internet because Portainer has more powers than Superman himself.</p>
<p>The solution? Using Tailscale, a mesh VPN that makes it easy to securely access services over a private network.</p>
<p>First, I needed to install Tailscale on my EC2 instance. And I did exactly that. Then, started Tailscale and logged in with my account to connect the EC2 instance to my Tailscale network.</p>
<p>Once Tailscale was up and running, it assigned a private IP to my EC2 instance, something like <code>100.x.x.x</code>. I noted this IP down because I’d be using it to access Portainer securely.</p>
<p>Now that my EC2 instance had a private Tailscale IP, I changed A record for <code>portainer.mydomain.com</code> in Cloudflare to point at that private IP.</p>
<p>With everything set up, I connected my laptop to the Tailscale network, which gave me access to the private IP of the EC2 instance.</p>
<p>Now, whenever I go to <code>portainer.mydomain.com</code>, it securely routes the traffic through the VPN, keeping Portainer unreachable from the public internet.</p>
<p>There was another hiccup: Cloudflare’s certificate only covers Cloudflare and my server, so when I used a private IP for Portainer, SSL went kaput.</p>
<p>To fix that, I grabbed an SSL certificate for the subdomain using ZeroSSL and installed it in Nginx. Problem solved!</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">I also blocked the SSH connection in my AWS security group, allowing me to SSH in my EC2 through tailscale only.</div>
</div>

<hr />
<h2 id="heading-final-words">Final Words</h2>
<p>Finally, I set up GitHub Actions for automatic deployments.</p>
<p>And that’s a wrap! From Dockerizing my app to setting up AWS and automating deployments, it’s been a wild ride.</p>
<p>I hope this helps if you’re on a similar journey. Feel free to drop any questions or thoughts in the comments. Cheers to seamless deployments!</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Getting Started with AWS]]></title><description><![CDATA[To get started, an AWS account is needed. Anyone can create an account on aws.amazon.com and get started instantly.
A credit card is compulsory to create an account.
Once the account is created, the name and other details can be changed via Account S...]]></description><link>https://blog.arjunsingh.com.np/getting-started-with-aws</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/getting-started-with-aws</guid><category><![CDATA[Cloud]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Tue, 30 Jul 2024 17:08:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BrunIOLQMfQ/upload/0eaf59b6248d135ce818f60610e2d9ca.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>To get started, an AWS account is needed. Anyone can create an account on aws.amazon.com and get started instantly.</p>
<p>A credit card is compulsory to create an account.</p>
<p>Once the account is created, the name and other details can be changed via Account Settings from the top right menu in the AWS Console Dashboard.</p>
<hr />
<h2 id="heading-identity-access-management-iam">Identity Access Management (IAM)</h2>
<p>AWS has a feature to manage multiple users in the same account. These users are called IAM users and can have different roles and permissions, which AWS calls groups and policies.</p>
<p>IAM users can be created by searching <code>IAM</code> in the top search bar and clicking on IAM under the services section. Doing this within an account is good practice.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Using MFA is recommended for users.</div>
</div>

<hr />
<h2 id="heading-aws-region-selector">AWS Region Selector</h2>
<p>Certain services in AWS are region-dependent. For example, EC2 instances can be created in different locations.</p>
<p>However, this is not true for every service in AWS. Services like Cloudfront, S3 Buckets, etc. are not created in any one specific region.</p>
<p>The active region can be changed from the top right dropdown (besides the Account menu). If any service created does not appear in the dashboard, the wrong region selection could be an issue.</p>
<hr />
<h2 id="heading-over-billing-story">Over Billing Story</h2>
<p>There are multiple stories about AWS overbilling rumored in the market. They are true.</p>
<p>Since AWS has a <strong>Pay as you Go</strong> policy, there are no monthly or annual costs. AWS charges for services according the usage. If an instance costs $1 per hour, the total amount for 2 instances in one hour would be $2.</p>
<p>If there are services that are created by mistake, or left on for a long time, it affects the billing. Even the default values while creating an instance should be noted carefully. Sometimes, larger variants are selected by default whereas smaller variants could be enough.</p>
<p>There are multiple AWS services to control the budget. Services like Budget Alerts and Billing Alarm could be used to control the spending on AWS.</p>
<p>There is also a free tier available. Visit the AWS pricing website for more details.</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[Cloud Concepts for Starters]]></title><description><![CDATA[Cloud Computing
Cloud computing is the practice of using network servers hosted on the internet to store, manage, and process data rather than a local server or a personal computer.
Evolution of Cloud Hosting

Dedicated Server

Virtual Private Server...]]></description><link>https://blog.arjunsingh.com.np/cloud-concepts</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/cloud-concepts</guid><category><![CDATA[AWS]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[Cloud Computing]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Sun, 28 Jul 2024 18:15:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Am6pBe2FpJw/upload/4e0d6de5a15a2c3e0fa9df8232b8bdbf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-cloud-computing">Cloud Computing</h2>
<p>Cloud computing is the practice of using network servers hosted on the internet to store, manage, and process data rather than a local server or a personal computer.</p>
<h3 id="heading-evolution-of-cloud-hosting">Evolution of Cloud Hosting</h3>
<ol>
<li><p>Dedicated Server</p>
</li>
<li><p>Virtual Private Server (VPS)</p>
</li>
<li><p>Shared Hosting</p>
</li>
<li><p>Cloud Hosting</p>
</li>
</ol>
<hr />
<h2 id="heading-amazon">Amazon</h2>
<p>Amazon is an American multinational computer technology corporation headquartered in Seattle, Washington. It was founded in 1994 by Jeff Bezos as an online bookstore.</p>
<h3 id="heading-amazon-services">Amazon Services</h3>
<ul>
<li><p>Amazon Web Services</p>
</li>
<li><p>Amazon Prime Video, Amazon Prime Music, Twitch.tv</p>
</li>
<li><p>Amazon Store</p>
</li>
<li><p>AI and Satellites</p>
</li>
<li><p>Many many more.</p>
</li>
</ul>
<p>Currently, the CEO of Amazon is Andy Jossy.</p>
<hr />
<h2 id="heading-amazon-web-services-aws">Amazon Web Services (AWS)</h2>
<p>Founded in 2006 as a Cloud Service Provider (CSP). However, Simple Queue Service (SQS) existed before, i.e. was launched in 2004.</p>
<p>After that, Simple Storage Service (S3) and Elastic Compute Cloud (EC2) were launched in March 2006 and August 2006 respectively.</p>
<p>Since April 2013, Amazon also started AWS Certification. Currently, the CEO of AWS is Matt Garman and the CTO of AWS is Werner Vogels.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">In November 2010, Amazon.com was migrated to AWS.</div>
</div>

<hr />
<h2 id="heading-cloud-service-providers-csps">Cloud Service Providers (CSPs)</h2>
<p>The company that provides multiple cloud services that can be chained together to create cloud architectures are called Cloud Service Providers.</p>
<p>All the features are accessible via a single unified API and utilize the metered billing (cost per usage). These providers also provide rich monitoring and IaaS (Infrastructure as a Service).</p>
<p><strong>Example: AWS</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722277776684/1fcaeec1-eeab-4d53-aee5-569e0c0bca02.jpeg" alt class="image--center mx-auto" /></p>
<p>If the company does not meet most of the requirements, they are referred to as Cloud Platforms. For example; Twillio, Hashicorp, etc.</p>
<h3 id="heading-landscape-of-csps">Landscape of CSPs</h3>
<ol>
<li><p><strong>Tier 1</strong></p>
<p> AWS, Azure, Google Cloud, Alibaba Cloud</p>
</li>
<li><p><strong>Tier 2</strong></p>
<p> IBM Cloud, Oracle Cloud, Huawei Cloud, Tencent</p>
</li>
<li><p><strong>Tier 3</strong></p>
<p> Vultr, Digital Ocean, Akamai Connected Cloud (Linode)</p>
</li>
<li><p><strong>Tier 4</strong></p>
<p> OpenStack, Apache CloudStack</p>
</li>
</ol>
<hr />
<h2 id="heading-common-cloud-services">Common Cloud Services</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>S.N.</td><td>Service</td><td>AWS Service</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>Compute</td><td>EC2 Virtual Machines</td></tr>
<tr>
<td>2</td><td>Storage</td><td>EBS Virtual Hard Drives</td></tr>
<tr>
<td>3</td><td>Database</td><td>RDS SQL Database</td></tr>
<tr>
<td>4</td><td>Networking</td><td>VPC Private Cloud Network</td></tr>
</tbody>
</table>
</div><p>AWS has 200+ cloud services such as; Analytics, Game Tech, Machine Learning, etc.</p>
<hr />
<h2 id="heading-evolution-of-computing">Evolution of Computing</h2>
<ol>
<li><p><strong>Dedicated</strong></p>
<p> Physical server utilized by a single customer.</p>
</li>
<li><p><strong>Virtual Machines</strong></p>
<p> Multiple virtual machines on one machine.</p>
</li>
<li><p><strong>Containers</strong></p>
<p> Multiple containers running on a virtual machine.</p>
</li>
<li><p><strong>Functions</strong></p>
<p> Serverless computing that runs only upon triggered.</p>
</li>
</ol>
<hr />
<h2 id="heading-types-of-cloud-computing">Types of Cloud Computing</h2>
<ul>
<li><p><strong>SaaS (Software as a Service)</strong></p>
<p>  These types of services are managed by service providers. They are specifically designed for customers.</p>
</li>
<li><p><strong>PaaS (Platform as a Service)</strong></p>
<p>  These services focus on the deployment and management of the application in the cloud. These services are targeted for developers.</p>
</li>
<li><p><strong>IaaS (Infrastructure as a Service)</strong></p>
<p>  This service provides access to the full architecture. These services are mostly targeted at admins and DevOps.</p>
</li>
</ul>
<hr />
<h2 id="heading-cloud-computing-deployment-models">Cloud Computing Deployment Models</h2>
<h3 id="heading-public-cloud">Public Cloud</h3>
<ul>
<li><p>Everything is built on the CSP</p>
</li>
<li><p>Also known as cloud-first or cloud-native</p>
</li>
<li><p>Suitable for startups, SaaS offerings</p>
</li>
</ul>
<h3 id="heading-private-cloud">Private Cloud</h3>
<ul>
<li><p>Everything is built on the company's data center</p>
</li>
<li><p>Also known as on-premise</p>
</li>
<li><p>Suitable for banks, fintech companies</p>
</li>
</ul>
<h3 id="heading-hybrid">Hybrid</h3>
<ul>
<li><p>Using both, on-premise and CSPs</p>
</li>
<li><p>Suitable for large enterprises</p>
</li>
</ul>
<h3 id="heading-cross-cloud">Cross-Cloud</h3>
<ul>
<li><p>Using multiple CSPs at once</p>
</li>
<li><p>Also known as multi-cloud</p>
</li>
<li><p>Suitable for enterprises with distributed environment</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Recursion in Programming]]></title><description><![CDATA[Introduction
Recursion in programming is a technique where a function calls itself directly or indirectly. This approach allows us to break down complex problems into smaller, more manageable chunks.
For an example,
def recursion():
    return recurs...]]></description><link>https://blog.arjunsingh.com.np/recursion</link><guid isPermaLink="true">https://blog.arjunsingh.com.np/recursion</guid><category><![CDATA[Python]]></category><category><![CDATA[Recursion]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Arjun Singh]]></dc:creator><pubDate>Thu, 27 Jun 2024 11:11:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720022585577/cb649f08-4b3e-4ec6-923b-a9250487c3ec.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Recursion in programming is a technique where a function calls itself directly or indirectly. This approach allows us to break down complex problems into smaller, more manageable chunks.</p>
<p>For an example,</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">recursion</span>():</span>
    <span class="hljs-keyword">return</span> recursion()
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">⏲</div>
<div data-node-type="callout-text">Wait, don't call this function yet.</div>
</div>

<p>It is essential to note that, there must be a base case and a recursive case in a function. If the base case is not mentioned, the function will call itself continuously and the system's stack will be full.</p>
<blockquote>
<p>That's how StackOverflow was found. Wait, what? Oops, that's when Stack Overflow exception is raised.</p>
</blockquote>
<hr />
<h2 id="heading-stack">Stack</h2>
<p>A stack is a special area of computer memory that stores information about a computer program's active subroutines or functions.</p>
<p>A new frame is added to the call stack each time a function is called. This frame contains the return address, local variables, parameters, and saved registers.</p>
<blockquote>
<p>Yes yes, the behavior is similar to stack that we read in data structures.</p>
</blockquote>
<hr />
<h2 id="heading-base-case-and-recursive-case">Base Case and Recursive Case</h2>
<ul>
<li><p><strong>Base case:</strong> A condition under which the function should stop calling itself, to prevent the infinite recursion.</p>
</li>
<li><p><strong>Recursive Case:</strong> The part of a function where it calls itself with a modified argument towards the base case.</p>
</li>
</ul>
<p>Let's take an example,</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_upto_one</span>(<span class="hljs-params">number</span>):</span>
    print(number)

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span>

    print_upto_one(number<span class="hljs-number">-1</span>)
</code></pre>
<p>Here, the function <code>print_upto_one</code> prints the passed <code>number</code>, calls itself again with decreased value. Also note that there is a condition to stop calling itself, i.e., when the value of <code>number</code> is <strong>1</strong>.</p>
<ul>
<li><p><code>if number == 1: return</code> is a base case where the function will stop calling itself.</p>
</li>
<li><p><code>print_upto_one(number-1)</code> is a recursive case when the function calls itself with a decreased value.</p>
</li>
</ul>
<hr />
<h2 id="heading-recursion-vs-infinite-loop">Recursion vs Infinite Loop</h2>
<blockquote>
<p>Wait, this sounds a lot like infinite loop. What's the difference?</p>
</blockquote>
<p>Not exactly. Let's understand it this way,</p>
<p><strong>Recursion</strong> is like Russian nesting dolls where each doll contains a smaller doll inside until you reach the smallest one.</p>
<p><strong>Infinite Loop</strong> is like a song stuck on repeat, playing the same part endlessly.</p>
<p>A new stack frame will be allocated to each function call in recursion whereas an infinite loop runs in the same amount of memory. That's why endless recursion will raise stack overflow error but infinite loop will keep running until the user or the system terminates it explicitly.</p>
<hr />
<h2 id="heading-detailed-working-of-recursion">Detailed Working of Recursion</h2>
<p>Recursion works in stack memory. Each function called inside the function returns the value from where it is called.</p>
<p>Meaning, let's assume we have a function <code>A</code> and each function call as <code>A1</code>, <code>A2</code>, <code>A3</code> and so on.</p>
<p>Now, when <code>A1</code> calls <code>A2</code> and <code>A2</code> calls <code>A3</code>, <code>A3</code> will return value to <code>A2</code> and <code>A2</code> will return value to <code>A1</code> that the caller function can process.</p>
<p>Let's understand this with an example. This function calculates the sum of n natural numbers.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sum</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    inner_func_value = sum(n - <span class="hljs-number">1</span>)
    <span class="hljs-keyword">return</span> n + inner_func_value
</code></pre>
<p><strong>Visual Representation</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Step</td><td>Function in Stack</td><td>Next Value (👇)</td><td>Return Value (👆)</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>sum(3)</td><td>3 + sum(2)</td><td>3 + 3 = 6</td></tr>
<tr>
<td>2</td><td>sum(2)</td><td>2 + sum(1)</td><td>2 + 1 = 3</td></tr>
<tr>
<td>3</td><td>sum(1)</td><td>1</td><td>1</td></tr>
</tbody>
</table>
</div><p>Here, the function calls itself with a decreased value until the passed value reaches to <strong>1</strong>. Then, every function output value is returned to the outer function, and so on.</p>
<blockquote>
<p>I know I know, this is a bit confusing while getting started.</p>
</blockquote>
<hr />
<h2 id="heading-factorial-of-a-number-using-recursion">Factorial of a number using Recursion</h2>
<p>Let's understand Recursion with one more example. This function will calculate the factorial of a number.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> n * factorial(n - <span class="hljs-number">1</span>)
</code></pre>
<p>Now, let's also understand the function calls step by step.</p>
<pre><code class="lang-plaintext">factorial(3)                        # 1st call with value 3
    3 * factorial(2)                # 2nd call with value 2 (3-1)
        3 * (2 * factorial(1))      # 3rd call with value 1 (2-1)
        3 * (2 * 1)                 # 3rd call returns 1 (base case)
    3 * 2                           # 2nd call returns 2 (2 * 1)
6                                   # 1st call returns 6 (3 * 2)
</code></pre>
<p>Let's break down each step:</p>
<ol>
<li><p><strong>First call</strong>: <code>factorial(3)</code></p>
<ul>
<li>Calculates 3 * factorial(2)</li>
</ul>
</li>
<li><p><strong>Second call</strong>: <code>factorial(2)</code></p>
<ul>
<li>Calculates 2 * factorial(1)</li>
</ul>
</li>
<li><p><strong>Third call</strong>: <code>factorial(1)</code></p>
<ul>
<li>Base case: Returns 1 since factorial(1) = 1</li>
</ul>
</li>
<li><p><strong>Return to second call</strong>:</p>
<ul>
<li><p>Calculates 2 * 1 = 2</p>
</li>
<li><p>Returns 2</p>
</li>
</ul>
</li>
<li><p><strong>Return to first call</strong>:</p>
<ul>
<li><p>Calculates 3 * 2 = 6</p>
</li>
<li><p>Returns 6</p>
</li>
</ul>
</li>
</ol>
<p>So, the factorial of 3 is correctly calculated as 6.</p>
<hr />
]]></content:encoded></item></channel></rss>