<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aamer Paul on Medium]]></title>
        <description><![CDATA[Stories by Aamer Paul on Medium]]></description>
        <link>https://medium.com/@aamernabi?source=rss-c9a52e47b81f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_wC4_Veto9TZkhW1j9vtdA.jpeg</url>
            <title>Stories by Aamer Paul on Medium</title>
            <link>https://medium.com/@aamernabi?source=rss-c9a52e47b81f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:09:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aamernabi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an AI Email Assistant with Prompt Chaining and LangGraph]]></title>
            <link>https://medium.com/@aamernabi/prompt-chaining-using-langgraph-609f213fbb5b?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/609f213fbb5b</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 13:09:41 GMT</pubDate>
            <atom:updated>2025-10-19T05:54:28.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oZ4rGJMQ0ZsbyZx0" /><figcaption>Image Source — <a href="https://unsplash.com/@googledeepmind">Google DeepMind</a></figcaption></figure><h3>Introduction</h3><p>Generative AI has unlocked solutions to problems previously considered impractical or even impossible to automate. Take email management, for example. The daily influx of client inquiries, meeting requests, and project updates, it can consume your entire workday. While simple AI solutions promise relief but they often fall short, generating generic and context-blind replies.</p><p>In this article, we will move beyond basic “one-shot” LLM prompts to build an intelligent email responder using <strong>Prompt Chaining</strong>, <strong>Context Engineering</strong>, and <strong>LangGraph</strong> for robust orchestration. We will build a sophisticated multi-step workflow that:</p><ol><li>Extracts <strong>intent</strong> and <strong>key information</strong> from an incoming email</li><li>Generates a <strong>structured outline</strong> for the response</li><li>Drafts the <strong>complete email body</strong></li><li>Rewrites the draft to match your <strong>desired tone</strong> (formal, friendly, etc.)</li></ol><p>By the end, you will have a clear understanding of how to decompose complex AI tasks into reliable workflows.</p><p>But before we dive into implementation, we need to understand what Prompt Chaining, Context Engineering, and LangGraph are.</p><h3>Prompt Chaining</h3><p>What is Prompt Chaining?</p><p><strong>Prompt chaining</strong> involves breaking down a complex task into a <strong>sequence of smaller, more manageable steps</strong>, with each step handled by a separate LLM prompt. The output from one prompt then serves as the input for the subsequent prompt, allowing the LLM to build a final solution incrementally. For example, one prompt could extract key entities from a document, and a second prompt could then use these entities to generate a summary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*765mznFA_gAdlzPUAy-Qjg.png" /><figcaption>Prompt chaining workflow</figcaption></figure><p>Prompt Chaining offers several advantages:</p><ul><li><strong>Improved Accuracy:</strong> The main advantage of the chaining prompts is that it allows iterative refinements, improving accuracy of the final output. However the downside of this workflow is latency. It trade offs latency for higher accuracy.</li><li><strong>Scalability:</strong> Chaining prompts allow generation of long or detailed content by breaking down into smaller, and manageable parts.</li></ul><p><strong>Why Prompt Chaining Matters</strong></p><p>This approach ensures each step has a focused responsibility, making the system more reliable and debuggable than a single monolithic prompt.</p><p>Examples where prompt chaining can be useful:</p><ul><li><strong>Content Creation:</strong> Generating detailed articles, stories, or scripts by chaining related prompts.</li><li><strong>Language Translation:</strong> Translating text across multiple languages using a chain of prompts to ensure accuracy and fluency.</li></ul><h3>Context Engineering</h3><p>LLMs are stateless, meaning they don’t retain memory of past interactions between calls. To get best results, we must provide an optimized <strong>context</strong> during each interaction.</p><p>Context refers to everything sent to the model in the prompt and can include:</p><ul><li>Instructions (what the model is supposed to do)</li><li>User input or questions</li><li>External data/documents (RAG)</li><li>State or history (e.g., tool calls, results from previous tool calls or prior messages in a conversation)</li><li>Expected output structure (e.g., response format, schema, or constraints)</li></ul><p><strong>Context engineering</strong> is the process of curating, structuring, and managing the input (context window) provided to a language model in order to maximize its performance on a given task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*fGzMvgfDVoNLrUUVKO6VKQ.png" /><figcaption>Context Engineering</figcaption></figure><h3>LangGraph</h3><p>In this article, we’ll use LangGraph to build an intelligent email responder.</p><p>But what exactly is LangGraph?</p><p><strong>LangGraph</strong> is an open-source AI agent framework, for building, deploying, and managing complex AI Agentic systems. It’s a low-level framework for building <strong>stateful</strong>, <strong>long-running</strong>, <strong>multi-actor</strong> agents and workflows.</p><p>Before we begin the implementation, let’s first understand the core concepts behind LangGraph.</p><h3>Core Concepts of LangGraph</h3><p>LangGraph is build on the concept of <strong>graph</strong>. In LangGraph, you build a graph, instead of linear chains (LangChain). This makes LangGraph better for complex workflows e.g. loops, branching, retries, multi-agent coordination</p><p>Following are the core concepts in LangGraph:</p><ol><li><strong>State</strong>:</li></ol><ul><li>Unlike LangChain’s memory, LangGraph uses a <strong>state object</strong> that is passed and updated as nodes run.</li><li>A state is a dictionary (TypedDict) of all variables your workflow needs. Its a data structure/context passed between steps.</li><li>Example:</li></ul><pre>class State(TypedDict):<br>  question: str<br>  classification: str | None<br>  answer: str | None</pre><p><strong>2. Nodes</strong>:</p><ul><li>A node is a function that takes in state and returns updates</li><li>Nodes can call LLMs, APIs, or some logic</li><li>Example:</li></ul><pre>def classify_node(state):<br>    q = state[&quot;question&quot;]<br>    if &quot;hello&quot; in q.lower():<br>        return {&quot;classification&quot;: &quot;greeting&quot;}<br>    return {&quot;classification&quot;: &quot;question&quot;}</pre><p><strong>3. Edges:</strong></p><ul><li>Edges connect nodes</li><li>They can be <strong>fixed</strong> (always go A → B) or <strong>conditional</strong> (branch depending on state)</li><li>LangGraph supports Control Flow: <br>- <em>Branching</em>: if condition X, go to Node ‘A’; else, go to Node ‘B’<br>- <em>Loops</em>: repeat until condition met (retry, re-ask user, refine)<br>- <em>Parallel</em>: run multiple nodes on a list and merge (map-reduce)</li></ul><p><strong>4. Tools:</strong></p><ul><li>Tool is a function or action that your agents can use to get something done like calling an API, doing a calculation, searching a database, or accessing a file.</li><li>Think of tools as skills or abilities that you give your agent.</li></ul><p><strong>5. Durable execution &amp; Checkpointing</strong>:</p><ul><li>LangGraph can pause and resume workflows</li><li>Useful for long-running agents or workflows with <a href="https://docs.langchain.com/oss/python/langgraph/add-human-in-the-loop">human approval</a></li></ul><p><strong>6. StateGraph</strong></p><ul><li>A graph that connects nodes and edges together</li><li>A StateGraph is a flowchart of steps (nodes) your AI agent goes through to complete a task</li></ul><h3>Setting up LangGraph</h3><p>This section will guide you through the process of installing and configuring LangGraph in your development environment.</p><ul><li>First ensure that Python 3.12 or later is installed on your machine</li><li>Create a Virtual Environment</li></ul><pre>python -m venv .<br>source langgraph_env/bin/activate </pre><ul><li>Install LangGraph dependencies</li></ul><pre>pip install langgraph python-dotenv<br>pip install langchain-openai   # integration package</pre><p>Set environment variable OPENAI_API_KEY.</p><pre>export OPENAI_API_KEY=&quot;your-api-key&quot;</pre><ul><li>Verify Installation</li></ul><pre>import langgraph<br><br>print(langgraph.__version__)</pre><h3>Implementation: Building Email Assistant Step by Step</h3><p>Now that we understand the core concepts, let’s start building AI Email Assistant using LangGraph. We’ll model the email response process as a structured pipeline where each step builds upon the previous one.</p><h3>Defining Processing Pipeline</h3><p>Our AI assistant will transform incoming emails into thoughtful responses through four distinct stages:</p><ul><li>Input: Raw email text</li><li>Step 1: Extract key information and intent</li><li>Step 2: Generate a structured response outline</li><li>Step 3: Draft the complete email body</li><li>Step 4: Apply tone transformation (professional, friendly, casual, etc.)</li><li>Output: Polished, context-aware email response</li></ul><p>The chain will look like following</p><p><strong>Chain:</strong></p><ol><li>Prompt 1 → “Extract intent and key info from incoming email”</li><li>Prompt 2 → “Generate a response outline”</li><li>Prompt 3 → “Draft complete email body”</li><li>Prompt 4 (Optional) → “Apply tone transformation (professional, friendly, casual, etc.)”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*ACY9ip6Ir23Ew42l.png" /></figure><h3>Implementation</h3><ol><li>Lets first define the tools and the model</li></ol><pre>import os<br>from typing import Any, Literal<br><br>from dotenv import load_dotenv<br>from langchain.chat_models import init_chat_model<br>from langchain_core.messages import AIMessage, HumanMessage, SystemMessage<br>from langchain_core.tools import tool<br>from langgraph.graph import END, START, StateGraph<br>from pydantic import BaseModel<br>from typing_extensions import TypedDict<br><br><br>load_dotenv()<br><br>@tool<br>def last_unread_email() -&gt; str:<br>    # your logic to retrieve last unread email<br>    return &quot;&quot;&quot;<br>    From: adam@example.com<br>    Date: 2024, Dec 12 14:00<br>    Subject: Bulk Order Inquiry<br><br>    Hi Neha,<br><br>    I’m reaching out to inquire about the availability of your product in bulk.<br>    We are looking to order around 500 units and would like to know the pricing and delivery timeline.<br>    Please get back to me by the end of the week.<br><br>    Best Regards,<br>    Adam Willson<br>    &quot;&quot;&quot;<br><br>tools = [last_unread_email]<br>tools_by_name = {tool.name: tool for tool in tools}<br>llm = init_chat_model(model=os.getenv(&quot;MODEL_NAME&quot;), model_provider=os.getenv(&quot;MODEL_PROVIDER&quot;), temperature=0)</pre><p>Make sure to add .env file with two variables:</p><pre>MODEL_PROVIDER=&lt;model-provider&gt;<br>MODEL_NAME=&lt;model-name&gt;</pre><p>2. Next, we define the state, which will consist of five fields:</p><ul><li><strong>email_text</strong>: Represents the raw incoming email content.</li><li><strong>extraction</strong>: A structured model that extracts the email’s intent, tone, questions, and urgency.</li><li><strong>reply_outline</strong>: A preliminary outline for drafting a response.</li><li><strong>full_email</strong>: The body of the drafted response.</li><li><strong>final_polished_email</strong>: The polished version of the email ready for sending.</li></ul><p>At each stage of processing, the state will be used and updated by the nodes.</p><pre>class EmailIntentExtraction(BaseModel):<br>    intent: str<br>    questions: list[str]<br>    tone: str<br>    urgency: str<br><br>    @classmethod<br>    def empty(cls) -&gt; &quot;EmailIntentExtraction&quot;:<br>        return EmailIntentExtraction(intent=&quot;&quot;, questions=[], tone=&quot;&quot;, urgency=&quot;&quot;)<br><br>class State(TypedDict):<br>    email_text: str<br>    extraction: EmailIntentExtraction<br>    reply_outline: str<br>    full_email: str<br>    final_polished_email: str</pre><p>3. The next step is to define the nodes, which can be call to LLM (Large Language Model), external APIs, or custom logic.</p><pre>def get_last_unread_email(state: State) -&gt; dict[str, Any]:<br>    llm_with_tools = llm.bind_tools(tools)<br>    message = llm_with_tools.invoke(<br>        [<br>            SystemMessage(content=&quot;You are a helpful assistant that can get unread emails.&quot;),<br>            HumanMessage(content=&quot;Get last unread mail from inbox&quot;),<br>        ]<br>    )<br><br>    # unnecessary: message is of type BaseMessage<br>    if not isinstance(message, AIMessage):<br>        return {}<br><br>    result = []<br><br>    if message.tool_calls:<br>        for tool_call in message.tool_calls:<br>            tool = tools_by_name[tool_call[&quot;name&quot;]]<br>            tool_result = tool.invoke(tool_call[&quot;args&quot;])<br>            result.append(tool_result)<br>    else:<br>        result.append(message.content)<br><br>    return {&quot;email_text&quot;: &quot;\n&quot;.join(result)}<br><br><br>def extract_intent_key_info(state: State) -&gt; dict[str, Any]:<br>    extraction_prompt = f&quot;&quot;&quot;<br>    Extract the following information from the email below:<br>    1. Sender&#39;s intent<br>    2. Specific questions or requests<br>    3. Tone of the email<br>    4. Urgency or deadline<br><br>    Email:<br>    \&quot;\&quot;\&quot;<br>    {state[&quot;email_text&quot;]}<br>    \&quot;\&quot;\&quot;<br><br>    Respond in JSON format.<br>    &quot;&quot;&quot;<br><br>    llm_with_structured_output = llm.with_structured_output(EmailIntentExtraction)<br><br>    message = llm_with_structured_output.invoke(<br>        [<br>            SystemMessage(content=&quot;You are a helpful assistant that extracts structured data from emails.&quot;),<br>            HumanMessage(content=extraction_prompt),<br>        ]<br>    )<br><br>    return {&quot;extraction&quot;: message}<br><br><br>def generate_reply_outline(state: State) -&gt; dict[str, Any]:<br>    extracted_info: EmailIntentExtraction = state[&quot;extraction&quot;]<br><br>    outline_prompt = f&quot;&quot;&quot;<br>    You are an email assistant.<br><br>    Based on the following extracted info, generate a structured email **outline** with these parts:<br>    1. Greeting<br>    2. Acknowledgment of the sender&#39;s intent<br>    3. Answers to questions or information needed<br>    4. Next steps or follow-up<br>    5. Closing<br><br>    Make sure the tone is {extracted_info.tone} and mention that a response will be sent before<br>    {extracted_info.urgency.lower()}.<br><br>    Extracted Info:<br>    {extracted_info.model_dump_json()}<br>    &quot;&quot;&quot;<br><br>    message = llm.invoke(<br>        [<br>            SystemMessage(<br>                content=&quot;You are a helpful assistant that generates email outlines based on extracted intent.&quot;<br>            ),<br>            HumanMessage(content=outline_prompt),<br>        ]<br>    )<br><br>    return {&quot;reply_outline&quot;: message.content}<br><br><br>def generate_full_reply_email(state: State) -&gt; dict[str, Any]:<br>    email_outline = state[&quot;reply_outline&quot;]<br>    compose_prompt = f&quot;&quot;&quot;<br>    Using the following email outline, write a professional and polite email reply.<br><br>    Format it as a formal business email. Keep the tone professional.<br><br>    Outline:<br>    {email_outline}<br>    &quot;&quot;&quot;<br>    message = llm.invoke(<br>        [<br>            SystemMessage(content=&quot;You are an AI that writes professional business emails based on outlines.&quot;),<br>            HumanMessage(content=compose_prompt),<br>        ]<br>    )<br><br>    return {&quot;full_email&quot;: message.content}<br><br><br>def __get_rewrite_prompt(email_text: str, tone: Literal[&quot;friendly&quot;, &quot;formal&quot;, &quot;casual&quot;, &quot;firm&quot;]):<br>    return f&quot;&quot;&quot;<br>    Rewrite the following email in a more **{tone}** tone.<br>    Keep all the original information intact, but adapt the language to fit the new tone.<br><br>    Email:<br>    \&quot;\&quot;\&quot;<br>    {email_text}<br>    \&quot;\&quot;\&quot;<br>    &quot;&quot;&quot;<br><br><br>def tone_rewriter(state: State) -&gt; dict[str, Any]:<br>    full_email = state[&quot;full_email&quot;]<br>    prompt = __get_rewrite_prompt(full_email, &quot;formal&quot;)<br><br>    message = llm.invoke(<br>        [<br>            SystemMessage(<br>                content=(<br>                    &quot;You are an assistant that rewrites emails in different tones while keeping the original meaning.&quot;<br>                )<br>            ),<br>            HumanMessage(content=prompt),<br>        ]<br>    )<br><br>    return {&quot;final_polished_email&quot;: message.content}</pre><p>4. Next, define the logic to determine whether to end the process (Conditional Gate). For example, you can check if the email contains at least 100 characters. You can also customize this logic to suit your specific requirements.</p><pre>def validate_incoming_email(state: State) -&gt; str:<br>    if len(state[&quot;email_text&quot;].strip()) &gt;= 100:<br>        return &quot;extract_intent_key_info&quot;<br>    return END</pre><p>5. Build workflow</p><pre>workflow = StateGraph(State)<br><br># Add nodes<br>workflow.add_node(&quot;get_last_unread_email&quot;, get_last_unread_email)<br>workflow.add_node(&quot;extract_intent_key_info&quot;, extract_intent_key_info)<br>workflow.add_node(&quot;generate_reply_outline&quot;, generate_reply_outline)<br>workflow.add_node(&quot;generate_full_reply_email&quot;, generate_full_reply_email)<br>workflow.add_node(&quot;tone_rewriter&quot;, tone_rewriter)<br><br># Add edges to connect nodes<br>workflow.add_edge(START, &quot;get_last_unread_email&quot;)<br>workflow.add_conditional_edges(&quot;get_last_unread_email&quot;, validate_incoming_email, [&quot;extract_intent_key_info&quot;, END])<br>workflow.add_edge(&quot;extract_intent_key_info&quot;, &quot;generate_reply_outline&quot;)<br>workflow.add_edge(&quot;generate_reply_outline&quot;, &quot;generate_full_reply_email&quot;)<br>workflow.add_edge(&quot;generate_full_reply_email&quot;, &quot;tone_rewriter&quot;)<br>workflow.add_edge(&quot;tone_rewriter&quot;, END)<br><br>chain = workflow.compile()</pre><p>6. Invoke the workflow</p><pre>initial_state = {<br>    &quot;email_text&quot;: &quot;&quot;,<br>    &quot;extraction&quot;: EmailIntentExtraction.empty(),<br>    &quot;reply_outline&quot;: &quot;&quot;,<br>    &quot;full_email&quot;: &quot;&quot;,<br>    &quot;final_polished_email&quot;: &quot;&quot;,<br>}<br>messages = chain.invoke(initial_state)<br><br>for key in messages:<br>    print(f&quot;{key}: &quot;)<br>    print(messages[key])<br>    print(&quot;---------------------------------------------&quot;)</pre><p>Finally, lets test our code</p><pre># Input emails<br>input_email = &quot;&quot;&quot;<br>From: adam@example.com<br>Date: 2024, Dec 12 14:00<br>Subject: Bulk Order Inquiry<br><br>Hi Neha,<br><br>I’m reaching out to inquire about the availability of your product in bulk.<br>We are looking to order around 500 units and would like to know the pricing and delivery timeline.<br>Please get back to me by the end of the week.<br><br>Best Regards,<br>Adam Willson<br>&quot;&quot;&quot;</pre><p>Result:</p><pre>extraction:<br>intent=&#39;Inquiring about bulk order&#39; questions=[&#39;What is the pricing for 500 units?&#39;, &#39;What is the delivery timeline for 500 units?&#39;] tone=&#39;Professional&#39; urgency=&#39;End of the week&#39;<br><br>---------------------------------------------<br><br>reply_outline:<br>Here is an email outline based on the information provided:<br><br>**Subject: Re: Bulk Order Inquiry - 500 Units**<br><br>1.  **Greeting**<br>    *   Dear [Sender Name],<br><br>2.  **Acknowledgment of Sender&#39;s Intent**<br>    *   Thank you for reaching out to us regarding your interest in a bulk order. We appreciate you considering our products.<br>    *   We understand you are specifically inquiring about the pricing and delivery timeline for 500 units.<br><br>3.  **Answers to Questions / Information Needed**<br>    *   We are currently compiling the detailed information regarding the pricing structure for 500 units and the estimated delivery timeline.<br>    *   Please be assured that we will send a comprehensive response addressing both of your questions before the end of the week.<br><br>4.  **Next Steps / Follow-up**<br>    *   We look forward to providing you with the necessary details and assisting you further with your bulk order.<br>    *   Should you have any additional questions in the meantime, please do not hesitate to contact us.<br><br>5.  **Closing**<br>    *   Sincerely,<br>    *   [Your Name/Company Name]<br><br>---------------------------------------------<br><br>full_email: <br>Subject: Re: Bulk Order Inquiry - 500 Units<br><br>Dear [Sender Name],<br><br>Thank you for reaching out to us regarding your interest in a bulk order. We appreciate you considering our products and understand you are specifically inquiring about the pricing and delivery timeline for 500 units.<br><br>We are currently compiling the detailed information regarding the pricing structure for 500 units and the estimated delivery timeline. Please be assured that we will send a comprehensive response addressing both of your questions before the end of the week.<br><br>We look forward to providing you with the necessary details and assisting you further with your bulk order. Should you have any additional questions in the meantime, please do not hesitate to contact us.<br><br>Sincerely,<br><br>[Your Name/Company Name]<br><br>---------------------------------------------<br><br>final_polished_email: <br>Subject: Re: Bulk Order Inquiry - 500 Units<br><br>Dear [Sender Name],<br><br>We acknowledge receipt of your inquiry regarding a bulk order. We appreciate your interest in our products and note your specific request concerning the pricing and estimated delivery timeline for 500 units.<br><br>We are currently in the process of compiling the comprehensive details pertaining to the pricing structure for 500 units and the projected delivery schedule. Please be advised that a comprehensive response addressing both of your inquiries will be dispatched prior to the close of this week.<br><br>We anticipate furnishing you with the requisite details and offering further assistance with your bulk order. Should you require any additional information or have further questions in the interim, please do not hesitate to contact us.<br><br>Sincerely,<br><br>[Your Name/Company Name]<br>---------------------------------------------</pre><h3>Conclusion</h3><p>In this article, we’ve built a sophisticated AI Email Assistant that demonstrates the power of modern LLM orchestration. By decomposing the complex task of email response into manageable steps using <strong>Prompt Chaining</strong>, we created a system that is more reliable, and effective than a single monolithic prompt.</p><p>This approach doesn’t just apply to email assistants, the same pattern can be applied to countless other AI applications, from customer support systems to content generation pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=609f213fbb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Pattern in Action]]></title>
            <link>https://medium.com/@aamernabi/strategy-pattern-in-action-solving-real-world-problems-98d8bbf393e4?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/98d8bbf393e4</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 16:35:04 GMT</pubDate>
            <atom:updated>2025-08-09T16:41:01.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I8KpL4wwIQGQYIQy" /><figcaption>Photo by <a href="https://unsplash.com/@markfb?utm_source=medium&amp;utm_medium=referral">Mark Fletcher-Brown</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Strategy Pattern</strong> is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime.</p><ul><li>You want to replace conditionals (if-else or switch) with <strong>polymorphism</strong>.</li><li>You need to switch behavior at runtime or make it configurable. Example: User selecting payment option</li><li>You want to define multiple ways of doing something (e.g., sorting, compression, payments).</li></ul><h3>Core Concepts</h3><p>The pattern consists of three main components:</p><ol><li><strong>Strategy</strong>: An interface or abstract class that defines a common method for all concrete strategies. The <strong>context</strong> uses this interface to call the algorithm.</li><li><strong>Concrete Strategy</strong>: The classes that implement the Strategy interface. Each class provides a specific implementation of the algorithm.</li><li><strong>Context</strong>: The class that holds a reference to a Strategy object. It uses the strategy’s method to perform a certain action. The context is unaware of the concrete strategy being used, it only interacts with the Strategy interface.</li></ol><h3>Example</h3><ol><li>Strategy Interface</li></ol><pre>public interface StrategyInterface {<br>    void example();<br>}</pre><p>2. Concrete Strategies</p><pre>class ConcreateStrategyImpl1 implements StrategyInterface {<br>  @Override<br>  public void example() {<br>    System.out.println(&quot;ConcreateStrategyImpl1: example()&quot;);<br>  }<br>}<br><br>class ConcreateStrategyImpl2 implements StrategyInterface {<br>  @Override<br>  public void example() {<br>    System.out.println(&quot;ConcreateStrategyImpl2: example()&quot;);<br>  }<br>}<br><br>class ConcreateStrategyImpl3 implements StrategyInterface {<br>  @Override<br>  public void example() {<br>    System.out.println(&quot;ConcreateStrategyImpl3: example()&quot;);<br>  }<br>}</pre><p>3. Context Class</p><pre>class StrategyContext {<br>    private StrategyInterface strategy;<br><br>    public StrategyContext() {}<br><br>    // optional - for example you want to provide default strategy<br>    public StrategyContext(StrategyInterface strategy) {<br>        this.strategy = strategy;<br>    }<br><br>    // Strategy can be changed at runtime<br>    public void setStrategy(StrategyInterface strategy) {<br>        this.strategy = strategy;<br>    }<br><br>    public void payAmount(double amount) {<br>        if (strategy == null) {<br>            throw new IllegalStateException(&quot;Payment strategy not set.&quot;);<br>        }<br>        strategy.example();<br>    }<br>}</pre><h3>Real world use-cases</h3><ul><li>Comparator&lt;T&gt; for sorting in Java</li><li>ThreadPoolExecutor with RejectedExecutionHandler</li><li>Logging frameworks (ConsoleLogger, FileLogger, RemoteLogger)</li></ul><h3>Parking Lot System Problem</h3><p>Let’s use Strategy Pattern to solve the problem. Let’s say we have design a <strong>Parking Lot system</strong>. It should assign an available parking spot to any vehicle that wants to park. The way spots are assigned can vary depending on different rules or criteria (eg: vehicle size, vip vehicle, ..). New requirements might also change how the system chooses a parking spot.</p><p>As you can see, there can be multiple ways to assign a parking spot. For example, larger vehicles like trucks may require dedicated spaces that differ from those used by regular cars. Also, we may get new requirements or there may be changes in the requirements. Using a traditional approach with multiple if-else or switch statements can quickly become hard to manage and scale. A better solution for this scenario is the Strategy Pattern, which allows us to define different spot assignment strategies based on specific criteria, making the system more flexible and maintainable.</p><p>Lets first define the strategy</p><ol><li>Define Strategy</li></ol><pre>// implementations will be like Car, Truck, SUV, Bike ..<br>interface Vehicle {<br>  String name();<br>}<br><br>interface ParkingStrategy {<br>  int findAvailableSlot(Vehicle vehicle);<br>}</pre><p>2. Concrete Strategies</p><p>Lets now define the Concrete Strategies. Let say we have 3 strategies:</p><ul><li>ClosestSpotParkingStrategy: Assign the nearest vacant spot to the entrance to reduce the time taken for vehicles to park.</li><li>TypeBasedParkingStrategy: Reserve specific spots for different types of vehicles (e.g., compact cars, oversized vehicles).</li><li>PriorityParkingStrategy: Implement priority parking for certain vehicles based on factors like membership status, VIP status, or special needs.</li></ul><pre>class ClosestSpotParkingStrategy implements ParkingStrategy {<br><br>  @Override<br>  public int findAvailableSlot(Vehicle vehicle) {<br>    System.out.println(&quot;Using closest spot parking strategy..&quot;);<br>    // fake spot number<br>    return 17; // implement closest spot parking logic<br>  }<br>}<br><br>class TypeBasedParkingStrategy implements ParkingStrategy {<br><br>  @Override<br>  public int findAvailableSlot(Vehicle vehicle) {<br>    System.out.println(&quot;Using type based parking strategy..&quot;);<br>    // fake spot number<br>    return 101; // implement type based spot parking logic<br>  }<br>}<br><br>class PriorityParkingStrategy implements ParkingStrategy {<br><br>  @Override<br>  public int findAvailableSlot(Vehicle vehicle) {<br>    System.out.println(&quot;Using priority parking strategy..&quot;);<br>    // fake spot number<br>    return 1011; // implement priority spot parking logic<br>  }<br>}</pre><p>We can easily create new strategies by implementing the ParkingStategy interface and implement the logic based on new requirements without modifying the existing code.</p><p>3. Define Context Class</p><pre>class ParkingLot {<br>  // default strategy<br>  private ParkingStrategy strategy = new ClosestSpotParkingStrategy();<br><br>  public ParkingLot() {}<br><br>  // or provide default strategy<br>  public ParkingLot(ParkingStrategy strategy) {<br>    this.strategy = strategy;<br>  }<br><br>  public void setParkingStrategy(ParkingStrategy strategy) {<br>    this.strategy = strategy;<br>  }<br><br>  public int parkVehicle(Vehicle vehicle) {<br>    int slot = strategy.findAvailableSlot(vehicle);<br>    System.out.println(&quot;Parking &quot; + vehicle.name() + &quot; in slot -&gt; &quot; + slot + &quot;.&quot;);<br>    return slot;<br>  }<br>}</pre><p>4. Client code implementation</p><pre>public class Application {<br><br>  public static void main(String[] args) {<br>    final var parkingLot = new ParkingLot();<br>    parkingLot.setParkingStrategy(new PriorityParkingStrategy());<br>    parkingLot.parkVehicle(new Car(&quot;Rolls-Royce&quot;));<br>  }<br>}</pre><h3>Drawbacks</h3><ul><li>The pattern can lead to explosion of classes and objects. For every new algorithm, you need to create a new concrete strategy class.</li><li>The client (or context) needs to be aware of the different available strategies to choose and instantiate the correct one.</li><li>While the pattern simplifies the context by removing conditional logic, it can introduce more complexity overall.</li><li>For very simple, straightforward algorithms, using a strategy interface and multiple classes can be overkill.</li></ul><h3>Conclusion</h3><p>The Strategy Pattern is a powerful behavioral design pattern that promotes flexibility and maintainability in your code. By encapsulating algorithms into separate classes (strategies), it allows you to switch between them at runtime, eliminating the need for complex conditional statements.</p><p>While Strategy Pattern introduces more classes, the benefits of decoupling the algorithm from the context often outweigh this drawback, especially in complex applications where behavior needs to change dynamically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98d8bbf393e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in Spring Boot 4.0? A Look Ahead]]></title>
            <link>https://medium.com/@aamernabi/whats-new-in-spring-boot-4-0-a-look-ahead-ff50b8b28d84?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff50b8b28d84</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 04:41:05 GMT</pubDate>
            <atom:updated>2025-07-25T05:48:50.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jEaDVr8jv6kXkfoQ" /><figcaption>Photo by <a href="https://unsplash.com/@anthonydelanoix?utm_source=medium&amp;utm_medium=referral">Anthony DELANOIX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Spring Boot 4.0 is a major release of the Spring Boot framework, introducing significant enhancements for developers. Spring Boot 4.0 is built upon <strong>Spring Framework 7.0</strong> which is major upcoming release of Spring Framework (projected for General Availability in November 2025).</p><p>Key features and improvements in Spring Boot 4 includes:</p><h3>Core Enhancements:</h3><p><strong>Java 17+ Baseline</strong></p><ul><li>Spring Boot 4 will <strong>require Java 17 or higher</strong> while at the same time recommending JDK 25 as the latest LTS release.</li><li>This baseline enables Spring Boot 4 to leverage the modern features of Java like pattern matching, sealed classes/interfaces, records, virtual threads and includes JVM level performance improvements.</li></ul><p><strong>Jakarta EE 11+</strong></p><ul><li>Spring Boot 4 supports Jakarta EE 11 and later, which means you have to move away from older javax.* and use jakarta.* instead.</li></ul><p><strong>Enhanced Native Compilation with AOT</strong></p><ul><li>Spring Boot 4 further refines native image generation using GraalVM and Ahead-of-Time (AOT) processing.</li></ul><p><strong>Kotlin 2.2+ Support</strong></p><ul><li>Spring Boot 4 introduces support for Kotlin 2.2+, enabling developers to leverage the latest features and improvements in the Kotlin language.</li></ul><p><strong>Micrometer 2.0+ Support</strong></p><ul><li>Spring Boot 4 is bundled with Micrometer 2.0+, offering better metrics, and improved observability support.</li></ul><p><strong>Spring Security 7 Integration</strong></p><ul><li>Includes enhanced security with OAuth 2.1 and OpenID Connect protection.</li></ul><p><strong>Improved Configuration Properties</strong></p><ul><li>Includes smarter record-based configuration with native hints for GraalVM and built-in validation.</li></ul><pre>@ConfigurationProperties(&quot;app.database&quot;)<br>public record DatabaseProperties(String url, String username, String password, int poolSize) {}</pre><p><strong>Null-Safety Improvements</strong></p><ul><li>The framework adopts JSpecify annotations to declare the null-safety of its API.</li></ul><h3>Other notable improvements</h3><h4>API Version Control</h4><p>The new update introduces streamlined support for API Versioning through annotations. This simplifies API evolution and maintenance.</p><p>Example:</p><pre>@RestController()<br>@RequestMapping(&quot;/greet&quot;)<br>class DemoController {<br>    @GetMapping(&quot;&quot;, version = &quot;1&quot;)<br>    fun greetV1(): Map&lt;String, String&gt; = mapOf(&quot;message&quot; to &quot;Hello! from greetV1()&quot;)<br><br>    @GetMapping(&quot;&quot;, version = &quot;2&quot;)<br>    fun greetV2(): Map&lt;String, String&gt; = mapOf(&quot;message&quot; to &quot;Hello! from greetV2()&quot;)<br>}</pre><p>To make above code work, you need to provide the ApiVersionStrategy. If you run above code without providing ApiVersionStrategy, app will throw:</p><pre>Caused by: java.lang.IllegalStateException: API version specified, but no ApiVersionStrategy configured</pre><p>Providing ApiVersionStrategy:</p><pre>@Configuration<br>class WebConfiguration : WebMvcConfigurer {<br> override fun configureApiVersioning(configurer: ApiVersionConfigurer) {<br>  configurer.useRequestHeader(&quot;X-API-Version&quot;)<br> }<br>}</pre><p>When calling api you have to provide the request header X-API-Version</p><pre>curl -H &quot;X-API-Version: 2&quot;  http://0.0.0.0:8080/greet<br><br># Response: {&quot;message&quot;:&quot;Hello! from greetV2()&quot;}</pre><h4>Programmatic Bean Registration (<strong>BeanRegistrar)</strong></h4><p>Spring Framework 7.0 introduces a new mechanism to register the bean programmatically using BeanRegistrar interface. This provides a more flexible approach to register a bean.</p><p>There are various benefits of providing the bean programmatically, for example, registering a bean based on some runtime conditions like active profiles.</p><p>Example:</p><pre>class Foo()<br>data class Bar(val value: String)<br><br>// you can also use BeanRegistrarDsl in Kotlin<br>class FooBarBeanRegistrar : BeanRegistrar {<br>    override fun register(<br>        registry: BeanRegistry,<br>        env: Environment<br>    ) {<br>        registry.registerBean(&quot;foo&quot;, Foo::class.java)<br><br>        // Register a bean with a custom supplier, potentially conditionally<br>        if (env.matchesProfiles(&quot;dev&quot;)) {<br>            registry.registerBean(Bar::class.java) { spec -&gt;<br>                spec.supplier { Bar(&quot;Bar_001&quot;) }<br>                    .prototype()<br>                    .lazyInit()<br>                    .description(&quot;Bar 001 description&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>Importing FooBarBeanRegistrar</p><pre>@Configuration<br>@Import(FooBarBeanRegistrar::class)<br>class AppConfig(<br>    private val foo: Foo,<br>    private val bar: Bar,<br>) {<br>    private val logger: Logger = LoggerFactory.getLogger(AppConfig::class.java)<br><br>    @Bean<br>    fun provideCommandLine(): CommandLineRunner = CommandLineRunner { args -&gt;<br>        logger.info(&quot;foo = $foo&quot;)<br>        logger.info(&quot;bar = $bar&quot;)<br>    }<br>}</pre><h4>Declarative HTTP interface</h4><p>Spring Boot 4 introduces enhanced support for declarative HTTP clients, building upon the existing RestClient and WebClient options.</p><p>It allows defining HTTP client interfaces using annotations, similar to Feign client. Spring generates the implementation at runtime, reducing boilerplate code for making HTTP requests.</p><p>Example:</p><pre>@HttpExchange(&quot;https://jsonplaceholder.typicode.com&quot;)<br>interface TodoClient {<br>    @GetExchange(&quot;/todos&quot;)<br>    fun getTodos(): List&lt;Todo&gt;<br><br>    @GetExchange(&quot;/todos/{id}&quot;)<br>    fun getTodoById(@PathVariable id: Long): Todo?<br><br>    @PostExchange(&quot;/todos&quot;)<br>    fun createTodo(@RequestBody todo: Map&lt;String, String&gt;)<br>}<br><br>@Configuration<br>@ImportHttpServices(TodoClient::class)<br>class ClientsConfiguration</pre><h3>Conclusion</h3><p>Spring Boot 4 aims to be a transformative release, setting a new standard for modern Java application development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff50b8b28d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Arrays and Masked Arrays in NumPy]]></title>
            <link>https://medium.com/@aamernabi/structured-array-and-masked-arrays-in-numpy-ce779991b939?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce779991b939</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 13:28:55 GMT</pubDate>
            <atom:updated>2025-07-29T08:58:20.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t_JCqd9i8xh9-494" /><figcaption>Photo by <a href="https://unsplash.com/@flousentimental?utm_source=medium&amp;utm_medium=referral">Thanh Nguyen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So far we’ve covered various important topics like getting started with <a href="https://medium.com/@aamernabi/a-deep-dive-into-numpy-arrays-77753e3a8bf5">Numpy</a>, doing <a href="https://medium.com/@aamernabi/numpy-operations-c996613800cc">operations</a> with Numpy, and <a href="https://medium.com/@aamernabi/numpy-array-manipulation-5f83fb111958">manipulating arrays</a>. In this post, we’ll dive into Structured Arrays and Masked Arrays in Numpy. These concepts will help us understand Numpy better and make our data manipulation tasks easier.</p><blockquote>Before diving in it’s important to note Structured Arrays can have performance implications compared to regular NumPy arrays due to their more complex memory layout. For very large datasets with complex data types, libraries like <a href="https://pandas.pydata.org/">pandas</a> often offer better performance and functionalities for data manipulation and analysis.</blockquote><h3>Structured Array</h3><p>Structured Arrays in NumPy allows to create arrays where each element can have multiple fields with different data types. Structured arrays provide a way to work with heterogeneous data in a uniform and efficient manner.</p><p>In the following example, we have NumPy Structured Array named users with three elements, each representing a user. Each element consists of three fields: id, name, and age. Here</p><ul><li>id is mapped to integer data type (int),</li><li>name is mapped to Unicode string data type (U10), which means strings with maximum length 10 characters,</li><li>age is mapped to unsigned 16-bit integer data type (uint16), which can hold values between 0 and 65535.</li></ul><pre>users = np.array(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;Andrew&#39;, 26)], <br>    dtype=[(&#39;id&#39;, &#39;int&#39;), (&#39;name&#39;, &#39;U10&#39;), (&#39;age&#39;, &#39;uint16&#39;)]<br>)<br>print(users) # [(1, &#39;Mark Taylo&#39;, 22) (2, &#39;Alice Joy&#39;, 31) (3, &#39;Andrew&#39;, 26)]<br><br>print(users[1]) # (2, &#39;Alice Joy&#39;, 31)<br><br>users[&quot;age&quot;][2] = 10<br><br>print(users) # [(1, &#39;Mark Taylo&#39;, 22) (2, &#39;Alice Joy&#39;, 31) (3, &#39;Andrew&#39;, 10)]</pre><p>You may have noticed the name of the first user is truncated to ‘Mark Taylo’ instead of ‘Mark Taylor’. This is because we have specified the data type of name as U10 and name cannot be longer than 10 characters.</p><h4>Array Creation</h4><p>There are several ways to create structured arrays in NumPy.</p><p><strong>Using List of Tuples</strong>: We can create a structured array by specifying the dtype parameter with a list of tuples, where each tuple represents a field in the array. Each tuple has the form (fieldname, datatype, shape) where shape is optional. If fieldname is the empty string, the field will be given a default name (like f#, where # is the integer index of the field).</p><pre># Creating a structured array using a list of tuples<br>user_dtype = np.dtype([<br>  (&#39;id&#39;, &#39;int&#39;), <br>  (&#39;name&#39;, &#39;U10&#39;), <br>  (&#39;points&#39;, &#39;uint8&#39;, (2,3))<br>])<br>users_data = [<br>    (1, &#39;Mark Taylor&#39;, [[85, 57, 76], [41, 31, 22]]),<br>    (2, &#39;Alice Joy&#39;, 31), <br>    (3, &#39;Andrew&#39;, [[71, 75, 54]])<br>]<br><br>print(user_dtype)<br># [(&#39;id&#39;, &#39;&lt;i8&#39;), (&#39;name&#39;, &#39;&lt;U10&#39;), (&#39;points&#39;, &#39;u1&#39;, (2, 3))]<br><br>users = np.array(users_data, dtype=user_dtype)<br>print(users)<br># [(1, &#39;Mark Taylo&#39;, [[85, 57, 76], [41, 31, 22]])<br>#  (2, &#39;Alice Joy&#39;, [[31, 31, 31], [31, 31, 31]])<br>#  (3, &#39;Andrew&#39;, [[71, 75, 54], [71, 75, 54]])]<br><br>print(users[&quot;points&quot;][0]) # [[85 57 76], [41 31 22]]</pre><p><strong>dtype with a String Format</strong>: We can create a structured array by specifying the dtype parameter with a string format. In this format, field names and data types are separated by commas. Field names are given the default names i.e f0, f1, etc when specifying dtype as string format.</p><pre># Creating a structured array using a string format<br><br># S5 specifies a fixed-length string field with length of 5 characters.<br>user_shorthand_type = np.dtype(&#39;int, S5, uint8&#39;)<br>print(user_shorthand_type)<br># [(&#39;f0&#39;, &#39;&lt;i8&#39;), (&#39;f1&#39;, &#39;S5&#39;), (&#39;f2&#39;, &#39;u1&#39;)]<br><br>users = np.array(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;Andrew&#39;, 26)], <br>    dtype=user_shorthand_type<br>)<br>print(users)<br># [(1, b&#39;Mark &#39;, 22) (2, b&#39;Alice&#39;, 31) (3, b&#39;Andre&#39;, 26)]</pre><p>We can also specify shape when using String format dtype. Example:</p><pre>custom_dtype = np.dtype(&#39;2int8, S20, (2, 3)u8&#39;)<br>print(custom_dtype)<br># [(&#39;f0&#39;, &#39;i1&#39;, (2,)), (&#39;f1&#39;, &#39;S20&#39;), (&#39;f2&#39;, &#39;&lt;u8&#39;, (2, 3))]<br><br>arr1 = np.array(<br>    [<br>        (1, &#39;Mark Taylor&#39;, [[85, 57, 76], [41, 31, 22]]),<br>        (2, &#39;Alice Joy&#39;, 31), <br>        (3, &#39;Andrew&#39;, [[71, 75, 54]])<br>    ], <br>    dtype=custom_dtype<br>)<br>print(arr1)<br># [([1, 1], b&#39;Mark Taylor&#39;, [[85, 57, 76], [41, 31, 22]])<br>#  ([2, 2], b&#39;Alice Joy&#39;, [[31, 31, 31], [31, 31, 31]])<br>#  ([3, 3], b&#39;Andrew&#39;, [[71, 75, 54], [71, 75, 54]])]</pre><p><strong>Using a Dictionary</strong>: We can create a structured array from a dictionary with two required keys, &#39;<strong>names</strong>&#39; and &#39;<strong>formats</strong>&#39;, and four optional keys, &#39;offsets&#39;, &#39;itemsize&#39;, &#39;aligned&#39; and &#39;titles&#39;.</p><ul><li>names represents list field names and formats represents list dtype specifications. Both must be of the same length.</li><li>offset specifies the byte offset of the field within the structure. It allows to control the memory layout of the structured array.</li><li>itemsize defines the total size of the field in bytes. For fixed-size data types like integers or floats, the item size is straightforward (e.g., 4 bytes for a 32-bit integer). For variable-length data types like strings or objects, the item size may vary depending on the content.</li><li>aligned value can be set to True to make the automatic offset computation use aligned offsets.</li><li>titles value should be a list of titles of the same length as names.</li></ul><pre>location_dtype = np.dtype({<br>    &#39;names&#39;: [&#39;id&#39;, &#39;location&#39;, &#39;latitude&#39;, &#39;longitude&#39;],<br>    &#39;formats&#39;: [&#39;i4&#39;, &#39;S2&#39;, &#39;f4&#39;, &#39;f4&#39;],<br>})<br>print(location_dtype)<br># [(&#39;id&#39;, &#39;&lt;i4&#39;), (&#39;location&#39;, &#39;S2&#39;), (&#39;latitude&#39;, &#39;&lt;f4&#39;), <br>#  (&#39;longitude&#39;, &#39;&lt;f4&#39;)]<br><br>arr2 = np.array(<br>    [<br>        (1, &quot;NY&quot;, 40.730610, -73.935242),<br>        (2, &quot;CA&quot;, 33.753746, -84.386330)<br>    ],<br>    dtype=location_dtype<br>)<br>print(arr2)<br># [(1, b&#39;NY&#39;, 40.73061 , -73.93524) (2, b&#39;CA&#39;, 33.753746, -84.38633)]</pre><p><strong>np.rec.fromrecords</strong>: We can also create a structured array from records using np.rec.fromrecords function. The data type (dtype) is automatically inferred from the provided records.</p><pre>arr4  = np.rec.fromrecords(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;Andrew&#39;, 26)],<br>    names=&#39;id, name, age&#39;<br>)<br><br>print(arr4.dtype)<br># (numpy.record, [(&#39;id&#39;, &#39;&lt;i8&#39;), (&#39;name&#39;, &#39;&lt;U11&#39;), (&#39;age&#39;, &#39;&lt;i8&#39;)])<br><br>print(arr4)<br># [(1, &#39;Mark Taylor&#39;, 22) (2, &#39;Alice Joy&#39;, 31) (3, &#39;Andrew&#39;, 26)]</pre><h4>Accessing and modifying Structured Array fields</h4><p>Accessing structured array fields in NumPy allows to retrieve specific fields or columns from the structured array. There are two main methods for accessing structured array fields: by field name and by field index.</p><pre>users = np.array(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;Andrew&#39;, 26)], <br>    dtype=[(&#39;id&#39;, &#39;int&#39;), (&#39;name&#39;, &#39;U10&#39;), (&#39;age&#39;, &#39;uint16&#39;)]<br>)<br><br># accessing by field name<br>print(users[&quot;id&quot;]) # [1 2 3]<br>print(users[&quot;name&quot;]) # [&#39;Mark Taylo&#39; &#39;Alice Joy&#39; &#39;Andrew&#39;]<br>print(users[&quot;age&quot;]) # [22 31 26]<br><br><br># accessing by field index<br>print(users[0]) # (1, &#39;Mark Taylo&#39;, 22)<br>print(users[1]) # (2, &#39;Alice Joy&#39;, 31)<br>print(users[2]) # (3, &#39;Andrew&#39;, 26)<br><br><br># we can also access specific item<br>print(users[&quot;name&quot;][2]) # Andrew</pre><p>Modifying structured array fields in NumPy allows to update specific fields or columns within the structured array.</p><pre>users = np.array(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;Andrew&#39;, 26)], <br>    dtype=[(&#39;id&#39;, &#39;int&#39;), (&#39;name&#39;, &#39;U50&#39;), (&#39;age&#39;, &#39;uint16&#39;)]<br>)<br><br># Modifying fields by name<br>users[&#39;age&#39;] += 5  # Increase the age of all elements by 5<br><br>print(users)<br># [(1, &#39;Mark Taylor&#39;, 27) (2, &#39;Alice Joy&#39;, 36) (3, &#39;Andrew&#39;, 31)]<br><br><br># We can also modify fields of a structured array using indices.<br>users[0][&quot;age&quot;] = 41<br>print(users)<br># [(1, &#39;Mark Taylor&#39;, 41) (2, &#39;Alice Joy&#39;, 36) (3, &#39;Andrew&#39;, 31)]</pre><h4>Sorting structured arrays</h4><p>Sorting structured arrays in NumPy allows to rearrange the elements of the array based on the values of one or more fields. NumPy provides the np.sort() function for sorting arrays. Example:</p><pre>users = np.array(<br>    [(1, &#39;Mark Taylor&#39;, 22), (2, &#39;Alice Joy&#39;, 31), (3, &#39;John Wayne&#39;, 19), <br>     (4, &#39;Andrew&#39;, 19)], <br>    dtype=[(&#39;id&#39;, &#39;int&#39;), (&#39;name&#39;, &#39;U50&#39;), (&#39;age&#39;, &#39;uint16&#39;)]<br>)<br><br># Sorting by a single field<br>sorted_users = np.sort(users, order=&#39;age&#39;)<br>print(sorted_users)<br># [(3, &#39;John Wayne&#39;, 19) (4, &#39;Andrew&#39;, 19) (1, &#39;Mark Taylor&#39;, 22)<br>#  (2, &#39;Alice Joy&#39;, 31)]<br><br># Sorting by a single field in descending order<br>sorted_users = np.sort(users, order=&#39;age&#39;)[::-1]<br>print(sorted_users)<br># [(2, &#39;Alice Joy&#39;, 31) (1, &#39;Mark Taylor&#39;, 22) (4, &#39;Andrew&#39;, 19)<br>#  (3, &#39;John Wayne&#39;, 19)]<br><br><br># Sorting by multiple fields<br>sorted_users = np.sort(users, order=[&#39;age&#39;, &#39;name&#39;])<br>print(sorted_users)<br># [(4, &#39;Andrew&#39;, 19) (3, &#39;John Wayne&#39;, 19) (1, &#39;Mark Taylor&#39;, 22)<br>#  (2, &#39;Alice Joy&#39;, 31)]</pre><p>We can also perform other operations on structured arrays, such as filtering, stacking, concatenating, and reshaping, similar to regular NumPy arrays.</p><h4>Use Cases</h4><ul><li><strong>Storing heterogeneous data</strong>: When working with data with different data types that naturally belong together, like student records (name: string, age: integer, height: float), structured arrays offer a compact and efficient way to store them.</li><li><strong>Interfacing external data sources</strong>: Structured arrays can be helpful when working with data from external sources like CSV files or database tables, where each row often represents a record with different data types.</li><li><strong>Custom data structures</strong>: We can use structured arrays to create custom data structures that group related data of different types, making code more organized and easier to understand.</li></ul><h3>Masked Arrays</h3><p>There may be scenarios, when we may have a dataset that is incomplete or tainted due to the presence of invalid data. NumPy provides numpy.ma module to convenient address this issue using Masked Arrays.</p><p><strong>Masked arrays</strong> in NumPy are a specialized arrays that allows us to efficiently handle the missing or invalid data. Masked arrays are particularly useful when dealing with data that contains missing or invalid values, where we want to ignore these values during calculations without explicitly removing them from the array.</p><pre>arr = np.array([1, 2, np.nan, 4, 5])<br>mask = np.isnan(arr)<br><br>masked_array = np.ma.array(arr, mask=mask)<br><br>print(masked_array.compressed()) # [1. 2. 4. 5.]<br>print(masked_array.mask) # [False False  True False False]<br>print(masked_array.mean()) # 3.0<br>print(masked_array * 2) # [2.0 4.0 -- 8.0 10.0]</pre><p>Note that we may get invalid result when performing numpy operation on arr without masking.</p><pre>print(np.mean(arr)) # nan<br>print(arr * 2) # [ 2.  4. nan  8. 10.] </pre><p>A masked array is combination of two components:</p><ol><li><strong>numpy.ndarray</strong> (Data Array): NumPy array that holds your actual data values.</li><li><strong>Mask</strong>: A mask is either nomask or a mask array. nomask indicates that no value of the associated array is invalid. mask array is a boolean array with the same shape as the data array. True elements in the mask indicate valid data in the corresponding position of the data array, while False elements indicate missing or invalid data. As in above example, the masked array has True value for element np.nan in array and False value for all the other elements.</li></ol><h4>Creating masked arrays</h4><p>There are several ways to create a masked array.</p><ol><li>np.ma.array: This is the most common and direct way to create a masked array. It takes arguments like: data and mask. We have already used this method in above example.</li><li>np.ma.masked_array: masked_array is an alias for the MaskedArray class. There is no verification of parameters, when using this method.</li><li>Using view of an existing array: arr.view(ma.MaskedArray)</li><li>There are several other functions available like np.ma.masked_equal, np.ma.masked_greater. You can check <a href="https://numpy.org/doc/stable/reference/maskedarray.generic.html#constructing-masked-arrays">here</a></li></ol><p>Example:</p><pre># masked_array<br>arr1 = np.array([1, 2, -1, 4, 5])<br>masked_arr1 = np.ma.masked_array(arr1, mask=arr1 &lt; 0)<br><br>print(masked_arr1.mask) # [False False  True False False]<br>print(masked_arr1.compressed()) # [1 2 4 5]<br><br># view of existing array<br>arr2 = np.array([0, 5, 0, 9, 12])<br>masked_arr2 = arr2.view(np.ma.MaskedArray)<br><br>print(masked_arr2.mask) # False<br>print(masked_arr2.compressed()) # [ 0  5  0  9 12]<br><br># masked_equals<br>arr3 = np.array([110, 112, -99, 114, -99, 116]) <br>masked_arr3 = np.ma.masked_equal(arr3, -99) <br><br>print(masked_arr3.mask)<br># [False False  True False  True False]<br>print(masked_arr3.compressed())<br># [110 112 114 116]</pre><h4>Accessing masked arrays</h4><p>There are several ways to access data within masked arrays in NumPy.</p><ol><li>Standard Indexing: we can access the data element of masked array like regular NumPy arrays.</li><li>Accessing valid data: we can use compressed() method to access the valid elements of array. This method returns a one-dimensional view of the masked array containing only the valid data elements.</li><li>Boolean indexing: masked_arr[masked_arr.mask == False]</li></ol><p>Example:</p><pre>arr = np.array([1, 2, np.nan, 4, 5, np.nan, 6, 7])<br>mask = np.isnan(arr)<br>masked_arr = np.ma.array(arr, mask=mask)<br><br># standard indexing<br>print(masked_arr[1]) # 2.0<br>print(masked_arr[1:5]) # [2.0 -- 4.0 5.0]<br><br># compressed method<br>print(masked_arr.compressed()) # [1. 2. 4. 5. 6. 7.]<br><br># Boolean masking<br>print(masked_arr[masked_arr.mask == False])<br># [1.0 2.0 4.0 5.0 6.0 7.0]</pre><p>To access the mask we can use field masked_arr.mask and to access the original data we can use field masked_arr.data</p><pre>print(masked_arr.mask)<br># [False False  True False False  True False False]<br>print(masked_arr.data)<br># [ 1.  2. nan  4.  5. nan  6.  7.]</pre><h4>Operations</h4><p>Just like regular numpy arrays, we can perform numpy operations on Masked Arrays while considering the mask, ensuring data integrity and excluding invalid entries from calculations. We can use the fill_value attribute of the masked array to specify a value to be used in place of masked elements during calculations.</p><p>Example:</p><pre>arr = np.array([1, 2, np.nan, 4, 5, np.nan, 6, 7])<br>mask = np.isnan(arr)<br>masked_arr = np.ma.array(arr, mask=mask)<br><br># Arithmetic Operations<br>print(masked_arr + 2)<br># [3.0 4.0 -- 6.0 7.0 -- 8.0 9.0]<br>print(masked_arr.filled(0) + 2)<br># [3. 4. 2. 6. 7. 2. 8. 9.]<br><br># Statistical Operations<br># (excludes NaN)<br>print(masked_arr.mean())<br># 4.166666666666667<br><br># Element-wise Operations<br>print(np.exp(masked_arr)) <br># [2.718281828459045 7.38905609893065 -- 54.598150033144236<br>#  148.4131591025766 -- 403.4287934927351 1096.6331584284585]<br><br># Comparison Operations<br>print(masked_arr &gt; 3)<br># [False False -- True True -- True True]</pre><h3>References:</h3><ul><li><a href="https://numpy.org/doc/stable/user/basics.rec.html">NumPy Structured Arrays</a></li><li><a href="https://numpy.org/doc/stable/reference/maskedarray.generic.html#constructing-masked-arrays">NumPy Masked Arrays</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce779991b939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NumPy Array Manipulation]]></title>
            <link>https://medium.com/@aamernabi/numpy-array-manipulation-5f83fb111958?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f83fb111958</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 06:39:14 GMT</pubDate>
            <atom:updated>2024-03-09T13:35:03.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uPvljV9mxz1LorXu" /><figcaption>Photo by <a href="https://unsplash.com/@jakobustrop?utm_source=medium&amp;utm_medium=referral">Jakob Braun</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to my blog series on NumPy. In this post, we’ll dive into the world of NumPy array manipulation, exploring how to reshape, combine, and split arrays for better data handling.</p><blockquote>Before diving in, be sure to check out my previous <a href="https://medium.com/@aamernabi/numpy-operations-c996613800cc">post</a>.</blockquote><p>In NumPy, arrays can be manipulated in various ways using a wide range of functions and methods. Here are some common approaches to array manipulation in NumPy.</p><h3>Reshaping</h3><p>NumPy provides functions like reshape, ravel, flatten, transpose to change the shape of an array. These functions does not modify the original array but returns a new array (except for ravel).</p><p>The reshape function gives a new shape to an array without modifying its data.</p><pre>arr1 = np.array([<br> [0, 1, 2, 3],<br> [6, 7, 8, 9],<br> [12, 13, 14, 15],<br>])<br><br>new_arr = arr1.reshape(6, 2)<br>print(new_arr)<br># [[ 0  1]<br>#  [ 2  3]<br>#  [ 6  7]<br>#  [ 8  9]<br>#  [12 13]<br>#  [14 15]]</pre><p>When using reshape function, we need to make sure the total number of elements remains the same in both shapes. For example, if we try to reshape the arr1 to shape (4, 4), we will get following error:</p><pre>arr1.reshape((4,4))<br>ValueError: cannot reshape array of size 12 into shape (4,4)</pre><p>If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated.</p><p>In following example, arr1.reshape(-1, 2), NumPy will automatically calculate the size for the first dimension such that the total number of elements remains the same after reshaping, and the second dimension will be set to 2. So, arr1.reshape(-1, 2) will reshape the array arr1 from shape (3, 4) to shape (6, 2).</p><pre>print(arr1.reshape(-1, 2))<br># [[ 0  1]<br>#  [ 2  3]<br>#  [ 6  7]<br>#  [ 8  9]<br>#  [12 13]<br>#  [14 15]]</pre><p>The transpose function returns an array with axes transposed.</p><pre>arr1 = np.array([<br> [0, 1, 2, 3],<br> [6, 7, 8, 9],<br> [12, 13, 14, 15],<br>])<br><br># transpose - after transpose shape is (4, 3)<br>print(np.transpose(arr1)) # or use `arr1.T`<br># [[ 0  6 12]<br>#  [ 1  7 13]<br>#  [ 2  8 14]<br>#  [ 3  9 15]]</pre><p>Both ravel and flatten are used to convert multi-dimensional arrays into one-dimensional arrays, but they differ in their behavior regarding memory management.</p><p><strong>ravel</strong>:</p><ul><li>Returns a flattened array, but it does not create a copy of the original array if the elements are contiguous in memory.</li><li>It returns a flattened view of the original array whenever possible.</li><li>If the memory layout of the original array is not contiguous, ravel will create a copy.</li><li>Changes made to the flattened array will affect the original array.</li></ul><p><strong>flatten</strong>:</p><ul><li>Always returns a copy of the original array, even if the memory layout is contiguous.</li><li>It ensures that the returned array is always a new array in memory.</li><li>Changes made to the flattened array will not affect the original array.</li></ul><pre>ravelled_arr = arr1.ravel()<br>flattened_arr = arr1.flatten()<br><br># modify first element<br>ravelled_arr[0] = 999<br>flattened_arr[1] = 888<br><br>print(&quot;original arr1: &quot;, arr1)<br># original arr1:<br># [[999   1   2   3]<br>#  [  6   7   8   9]<br>#  [ 12  13  14  15]]<br>print(&quot;ravelled arr: &quot;, ravelled_arr)<br># ravelled arr:  [999   1   2   3   6   7   8   9  12  13  14  15]<br>print(&quot;flattened arr: &quot;, flattened_arr)<br># flattened arr:  [  0 888   2   3   6   7   8   9  12  13  14  15]</pre><p>We can see in above example, changes in ravelled_arr are reflected in original array arr1.</p><h3>Concatenation and Splitting</h3><p>NumPy provides functions like concatenate, stack, hstack, vstack for combining arrays along different axes, and functions like split, hsplit, vsplit for splitting arrays into smaller ones. Lets start with <strong>Concatenation</strong> first.</p><p>concatenate(): Concatenates arrays along a specified axis.</p><pre>arr1 = np.array([[1, 2, 3], [3, 4, 6]])<br>arr2 = np.array([[5, 6, 7]])<br><br>arr3 = np.concatenate((arr1, arr2))<br>print(arr3)<br># [[1 2 3]<br>#  [3 4 6]<br>#  [5 6 7]]<br><br><br>arr1 = np.array([[1, 2], [3, 4]])<br>arr2 = np.array([[5, 6, 7], [8, 9, 10]])<br><br>arr3 = np.concatenate((arr1, arr2), axis=1)<br>print(arr3)<br># [[ 1  2  5  6  7]<br>#  [ 3  4  8  9 10]]</pre><p><em>Note: The shapes of the arrays must be compatible along the specified axis for concatenation to occur without errors.</em></p><p>vstack and hstack:</p><ul><li>vstack stacks arrays vertically (along axis 0).</li><li>hstack stacks arrays horizontally (along axis 1).</li></ul><pre># Stacking arrays vertically<br>arr1 = np.array([[1, 2, 3], [4, 5, 6]])<br>arr2 = np.array([[7, 8, 9]])<br>stacked_vertically = np.vstack((arr1, arr2))<br>print(stacked_vertically)<br># [[1 2 3]<br>#  [4 5 6]<br>#  [7 8 9]]<br><br># Stacking arrays horizontally<br>arr3 = np.array([[7, 8], [9, 10]])<br>stacked_horizontally = np.hstack((arr1, arr3))<br>print(stacked_horizontally)<br># [[ 1  2  3  7  8]<br>#  [ 4  5  6  9 10]]</pre><p><strong>Splitting:</strong></p><p>NumPy provides functions to split arrays into smaller ones. Following are some of the common functions for splitting arrays in NumPy. Also, just for readability lets define a function that prints the splitted array.</p><pre>def print_arr(arr):<br>    for e in arr:<br>        print(e)</pre><p>split(): Splits an array into multiple sub-arrays along a specified axis.</p><pre>arr1 = np.arange(9) # [0 1 2 3 4 5 6 7 8]<br>split_arr = np.split(arr1, 3)<br>print_arr(split_arr)<br># [0 1 2]<br># [3 4 5]<br># [6 7 8]<br><br># we can also specify `axis`<br>arr1 = np.array([[1, 2, 3, 4, 5, 6],<br>                [7, 8, 9, 10, 11, 12]])<br>split_arr = np.split(arr1, 3, axis=1)<br>print_arr(split_arr)<br># [[1 2], [7 8]]<br># [[ 3  4], [ 9 10]]<br># [[ 5  6], [11 12]]</pre><p>hsplit and vsplit:</p><ul><li>hsplit splits an array horizontally (along axis 1).</li><li>vsplit splits an array vertically (along axis 0).</li></ul><pre># Splitting an array horizontally into 3 sub-arrays<br>arr1 = np.array([[1, 2, 3], [4, 5, 6]])<br>h_split = np.hsplit(arr1, 3)<br>print_arr(h_split)<br># [[1], [4]]<br># [[2], [5]]<br># [[3], [6]]<br><br># Splitting an array vertically into 3 sub-arrays<br>arr1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])<br>v_split = np.vsplit(arr1, 3)<br>print_arr(v_split)<br># [[1 2 3]]<br># [[4 5 6]]<br># [[7 8 9]]</pre><p>We can also specify the number of sub-arrays we want along the corresponding axis. Here’s an example:</p><pre># Creating an array with shape (6, 4)<br>arr1 = np.arange(24).reshape(6, 4)<br><br># Splitting the array vertically into 3 sub-arrays (2 rows, and 4 columns)<br>v_split = np.vsplit(arr1, (2, 4))<br>print_arr(v_split)<br># [[0 1 2 3], [4 5 6 7]]<br># [[ 8  9 10 11], [12 13 14 15]]<br># [[16 17 18 19], [20 21 22 23]]</pre><h3>Adding and Removing Elements:</h3><p>NumPy provides functions like append, insert, and delete add or remove elements from arrays. Theses functions does not modify the original array in place. Instead, they return a new array with the desired modifications applied.</p><ol><li>append: appends elements to the end of the array along the specified axis.</li><li>insert: inserts elements before the given index along the specified axis.</li><li>delete: deletes elements at the specified index along the specified axis.</li></ol><pre># Appending<br>arr1 = np.full((2, 3), 99)<br>new_arr = np.append(arr1, [1, 2, 3])<br>print(new_arr)<br># [99 99 99 99 99 99  1  2  3]</pre><p>When axis is specified, values must have the correct shape. new_arr = np.append(arr1, [1, 2, 3], axis=0) will throw error:</p><p><em>“ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)”</em></p><pre>arr1 = np.full((2, 3), 99)<br>new_arr = np.append(arr1, [[1, 2, 3]], axis=0)<br>print(new_arr)<br># [[99 99 99]<br>#  [99 99 99]<br>#  [ 1  2  3]]<br><br>new_arr = np.append(arr1, [[1], [2]], axis=1)<br>print(new_arr)<br># [[99 99 99  1]<br>#  [99 99 99  2]]</pre><pre># Inserting Elements<br>arr1 = np.full((2, 3), 99)<br>new_arr = np.insert(arr1, 1, 5)  # Insert 5 at index 1<br>print(new_arr)<br># [99  5 99 99 99 99 99]<br><br>new_arr = np.insert(arr1, 1, 5, axis=0)  # Insert row [5, 5, 5] at index 1<br>print(new_arr)<br># [[99 99 99]<br>#  [ 5  5  5]<br>#  [99 99 99]]</pre><pre># Deleting elements<br>arr1 = np.arange(1, 10).reshape((3, 3))<br>print(arr1)<br># [[1 2 3]<br>#  [4 5 6]<br>#  [7 8 9]]<br><br>new_arr = np.delete(arr1, 2)  # Delete element at index 2<br>print(new_arr)<br># [1 2 4 5 6 7 8 9]<br><br>new_arr = np.delete(arr1, 2, axis=1)  # Delete third column <br>print(new_arr)<br># [[1 2]<br>#  [4 5]<br>#  [7 8]]</pre><h3>Sorting</h3><p>In NumPy, sorting refers to arranging the elements of an array in a particular order, typically in ascending or descending order. NumPy provides several functions for sorting arrays.</p><p><strong>np.sort()</strong>:</p><ul><li>This function returns a sorted copy of an array.</li><li>By default, it sorts the array along the last axis. However, we can specify the axis along which to sort using the axis parameter. (axis: default value is -1)</li><li>It does not modify the original array; instead, it returns a new array with elements sorted.</li><li>We can select the sorting algorithm by specifying the kind argument, which accepts options such as {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’} (optional).</li></ul><p>Example:</p><pre>arr1 = np.array([3, 1, 2])<br>sorted_arr = np.sort(arr1)<br>print(sorted_arr)  <br># [1 2 3]</pre><p><strong>np.argsort()</strong>:</p><ul><li>This function returns the indices that would sort an array.</li><li>Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.</li><li>Instead of sorting the array itself, it returns an array of indices that specify the order of elements when sorted.</li><li>It can be useful when you need to sort one array based on the order of another array.</li></ul><p>Example:</p><pre>arr1 = np.array([3, 1, 2])<br>indices = np.argsort(arr1)<br>print(indices)  <br># [1 2 0]</pre><p><strong>ndarray.sort()</strong>:</p><ul><li>This method sorts the array in place.</li><li>Unlike np.sort(), it modifies the original array.</li><li>We can select the sorting algorithm by specifying the kind argument, which accepts options such as {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’} (optional).</li></ul><p>Example:</p><pre>arr1 = np.array([3, 1, 2])<br>arr1.sort()<br>print(arr1)  <br># [1 2 3]</pre><p><strong>np.lexsort()</strong>:</p><ul><li>This function performs an indirect sort using a sequence of keys.</li><li>It is useful for sorting multiple arrays based on a single sort key.</li></ul><p>Example: (Sort names: first by last_name, then by first_name)</p><pre>first_names = (&#39;Mark&#39;, &#39;Amy&#39;, &#39;John&#39;)<br>last_names =    (&#39;Taylor&#39;, &#39;Walker&#39;, &#39;Ason&#39;)<br>result = np.lexsort((first_names, last_names)) # Sort &#39;last_names&#39; first, then &#39;firstnames&#39;<br>print(result)<br># [2 0 1]</pre><h3>Unique and Set Operations:</h3><p>In NumPy, <strong>unique</strong> and <strong>set operations</strong> refer to functions for identifying unique elements in arrays and performing set operations on arrays. These operations are useful for data manipulation and analysis tasks. Lets start with unique operations first.</p><h4>Unique Operations:</h4><p><strong>np.unique()</strong>:</p><ul><li>The function returns the sorted unique elements of an array.</li><li>When the parameter return_index is set to True, the function also returns the indices of the original array corresponding to the unique sorted array elements.</li><li>When the parameter return_inverse is set to True, the function also returns an array (indices) that maps the original array to the unique values. The returned indices can be used to reconstruct array.</li></ul><p>Example:</p><pre>arr1 = np.array([2, 3, 1, 4, 1, 2, 4])<br>unique_elements = np.unique(arr1)<br>print(unique_elements)  <br># [1 2 3 4]<br><br>_, unique_elements_indicies = np.unique(arr1, return_index=True)<br>print(unique_elements_indicies) <br># [2 0 1 3]<br><br>_, unique_elements_indicies = np.unique(arr1, return_inverse=True)<br>print(unique_elements_indicies) <br># [1 2 0 3 0 1 3]</pre><p><strong>np.in1d()</strong>:</p><ul><li>This function tests whether each element of a 1D array is also present in a second array.</li><li>It returns a boolean array of the same shape as the first array, indicating whether each element is found in the second array.</li><li>When parameter invert is set to True, it inverts the boolean array.</li></ul><p>Example:</p><pre>arr1 = np.array([1, 2, 3, 4])<br>arr2 = np.array([2, 3, 7])<br>result = np.in1d(arr1, arr2)<br>print(result)<br># [False  True  True False]<br><br>result = np.in1d(arr1, arr2, invert=True)<br>print(result)<br># [ True False False  True]</pre><h4>Set Operations</h4><ol><li><strong>Union</strong>: Combines unique elements from multiple arrays into a single array.</li><li><strong>Intersection</strong>: Returns the common elements between two arrays.</li><li><strong>Set Difference</strong>: Returns the elements that are unique to the first array but not present in the second array.</li><li><strong>Symmetric Difference</strong>: Returns the elements that are unique to each array.</li></ol><p>Example:</p><pre># union<br>arr1 = np.array([1, 2, 3])<br>arr2 = np.array([2, 3, 4, 5])<br>union = np.union1d(arr1, arr2)<br>print(union)  <br># [1 2 3 4 5]<br><br># intersection<br>intersection = np.intersect1d(arr1, arr2)<br>print(intersection)  <br># [2 3]<br><br># Set Difference<br>difference = np.setdiff1d(arr1, arr2)<br>print(difference)  <br># [1]<br><br># Symmetric Difference<br>symmetric_difference = np.setxor1d(arr1, arr2)<br>print(symmetric_difference)  <br># [1 4 5]</pre><h3>Reference</h3><ul><li><a href="https://numpy.org/doc/stable/reference/routines.array-manipulation.html">https://numpy.org/doc/stable/reference/routines.array-manipulation.html</a></li><li><a href="https://numpy.org/doc/stable/reference/generated/numpy.sort.html">https://numpy.org/doc/stable/reference/generated/numpy.sort.html</a></li></ul><blockquote>Next <a href="https://medium.com/@aamernabi/structured-array-and-masked-arrays-in-numpy-ce779991b939">Numpy Structured Array</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f83fb111958" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numpy Operations]]></title>
            <link>https://medium.com/@aamernabi/numpy-operations-c996613800cc?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c996613800cc</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 13:09:48 GMT</pubDate>
            <atom:updated>2024-03-09T13:36:40.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zDEan56i0OYmZnul" /><figcaption>Photo by <a href="https://unsplash.com/@dominikhofbauer?utm_source=medium&amp;utm_medium=referral">dominik hofbauer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we will delve into NumPy operations, exploring the core functionalities and demonstrating how to perform various mathematical and array manipulation in NumPy. From basic arithmetic operations to advanced linear algebra functions, NumPy offers a comprehensive set of tools to tackle complex computational challenges effectively.</p><blockquote>Before diving in, be sure to check out my previous <a href="https://medium.com/@aamernabi/a-deep-dive-into-numpy-arrays-77753e3a8bf5">post</a>.</blockquote><p>NumPy includes a wide range of mathematical functions and operations. Some of the key mathematical operations provided by NumPy are:</p><h3>Basic arithmetic operations:</h3><p>NumPy’s <strong>arithmetic operators</strong> on arrays perform elementwise operations, meaning each element in the input arrays is operated upon individually. A new array is created and filled with the results of the arithmetic operation. Some of the arithmetic functions in NumPy include:</p><ol><li>Addition: np.add(a, b) or a + b</li><li>Subtraction: np.subtract(a, b) or a - b</li><li>Multiplication: np.multiply(a, b) or a * b</li><li>Division: np.divide(a, b) or a / b</li><li>Floor division: np.floor_divide(a, b) or a // b</li><li>Exponentiation: np.power(a, b) or a ** b</li><li>Modulus: np.mod(a, b) or a % b</li></ol><p>Example:</p><pre>import numpy as np<br><br>arr1 = np.array([2, 4, 6, 8])<br>print(arr1 + 2) # [ 4  6  8 10]</pre><p>In above example, 2 is added to each element in the array arr1. A new array is created and filled with the result of the operation. We can also use NumPy&#39;s add function instead of + operator. Same applies to other mathematical operations.</p><pre>np.subtract(arr1, 2) # [0 2 4 6]<br>np.multiply(arr1, 2) # [ 4  8 12 16]<br>arr1 / 2 # [1. 2. 3. 4.]<br>arr1 // 2 # [1 2 3 4]<br>arr1 % 2 # [0 0 0 0]<br>arr1 **= 2 # modifies existing array rather than create a new one.<br>print(arr1) # [ 4 16 36 64]</pre><p>We can also perform operations on multiple arrays.</p><pre>arr1 = np.array([2, 4, 6, 8])<br>arr2 = np.arange(1, 5)<br><br>arr1 + arr2 # [ 3  6  9 12]<br>np.floor_divide(arr1, arr2) # [2 2 2 2]<br>arr3 = arr1 * arr2<br>arr1 * arr2 * arr3 # [   4   64  324 1024]</pre><p>When operating with arrays of different types, the resultant array type corresponds to the more general or precise one (a behavior known as upcasting).</p><pre>arr1 = np.array([2, 4, 6, 8]) # array of type int<br>arr2 = np.arange(1, 5, dtype=float) # array of type float<br>arr1 + arr2 # [ 3.  6.  9. 12.] # upcasted to float</pre><h4><strong>Broadcasting</strong></h4><p>In the above examples, you may have noticed that we were able to perform arithmetic operations between scalars and arrays seamlessly. This capability is made possible by broadcasting.</p><p><strong>Broadcasting</strong> allows arithmetic operations to be performed on arrays of different shapes. The broadcasting rule in NumPy states that arrays with smaller dimensions are padded with ones on their leading (left) side to match the shape of the arrays with larger dimensions. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.</p><pre>a = np.array([1, 2, 3], dtype=int)<br># define a scalar<br>b = 2<br># multiply by array by a scalar<br>print(a * b) #[2 4 6]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*D4pPxzcG_qAx2hVYa_HT8w.png" /><figcaption>Broadcasting Example</figcaption></figure><p>The above example is similar to:</p><pre>a = np.array([1, 2, 3], dtype=int)<br>b = np.array([2, 2, 2], dtype=int)<br>print(a * b)</pre><h3>Trigonometric functions:</h3><p><strong>Trigonometric functions</strong> operate elementwise on arrays, applying the trigonometric operation to each element in the array. NumPy provides various trigonometric functions commonly used in mathematics and scientific computing. Some of the key trigonometric functions in NumPy include:</p><ol><li>Sine: np.sin(x)</li><li>Cosine: np.cos(x)</li><li>Tangent: np.tan(x)</li><li>Inverse sine: np.arcsin(x)</li><li>Inverse cosine: np.arccos(x)</li><li>Inverse tangent: np.arctan(x)</li></ol><p>These functions accepts array as input and return a new array containing the computed trigonometric values for each element. The input array can be one-dimensional or multidimensional.</p><p>Example:</p><pre>np.sin(90) # 0.8939966636005579<br>arr1 = np.array([45, 90, 180, 360])<br>np.sin(arr1) # [ 0.85090352  0.89399666 -0.80115264  0.95891572]<br>np.arctan(arr1) # [1.54857776 1.55968567 1.56524083 1.56801856]</pre><h3>Hyperbolic functions:</h3><p><strong>Hyperbolic functions</strong> in NumPy are mathematical functions that operate elementwise on arrays, applying the hyperbolic operation to each element in the array.</p><ol><li>Hyperbolic sine: np.sinh(x)</li><li>Hyperbolic cosine: np.cosh(x)</li><li>Hyperbolic tangent: np.tanh(x)</li></ol><p>Example:</p><pre>arr1 = np.array([45, 90, 180, 360])<br>np.cosh(arr1) # [1.74671355e+019 6.10201647e+038 7.44692100e+077 1.10913265e+156]</pre><h3>Exponential and logarithmic functions</h3><p><strong>Exponential and logarithmic functions</strong> are mathematical functions that operate on input values to compute exponential and logarithmic transformations, respectively. In NumPy, these functions operate elementwise on arrays.</p><ol><li>Exponential: np.exp(x)</li><li>Natural logarithm: np.log(x)</li><li>Logarithm base 10: np.log10(x)</li><li>Logarithm base 2: np.log2(x)</li></ol><p>Example:</p><pre>np.exp(arr1) # [3.49342711e+019 1.22040329e+039 1.48938420e+078 2.21826530e+156]<br>np.log10(arr1) # [1.65321251 1.95424251 2.25527251 2.5563025 ]</pre><h3>Linear algebra</h3><p>NumPy offers a comprehensive set of functions for <strong>Linear Algebra</strong> computations. Some of the key linear algebra operations provided by NumPy are:</p><ol><li>Matrix multiplication: np.dot(a, b) or a @ b</li><li>Vector dot product: np.dot(a, b) - Computes the dot product of two vectors.</li><li>Determinant: np.linalg.det(a)</li><li>Inverse: np.linalg.inv(a) - Computes the inverse of a square matrix.</li><li>Transpose: np.transpose(a) or a.T</li><li>Trace: np.trace(a) - Computes the sum of the diagonal elements of a matrix.</li><li>Eigenvalues and eigenvectors: np.linalg.eig(a) - Computes the eigenvalues and eigenvectors of a square matrix.</li></ol><p>These are few examples of Linear Algebra operations provided in NumPy. These operations accept NumPy arrays as input and return NumPy arrays or scalars as output. These functions perform operations on matrices and vectors according to the rules of Linear Algebra.</p><p>Example:</p><pre>arr1 = np.ones((4, 2), dtype=int)<br>arr2 = np.full((2, 4), 2, dtype=int)<br><br># results in 4x4 matrix<br>np.dot(arr1, arr2)<br># [[4 4 4 4]<br>#  [4 4 4 4]<br>#  [4 4 4 4]<br>#  [4 4 4 4]]<br><br>arr1 = np.arange(1, 10, dtype=int).reshape((3,3))<br>arr2 = np.arange(10, 19, dtype=int).reshape((3,3))<br>arr2.T<br># [[10 13 16]<br>#  [11 14 17]<br>#  [12 15 18]]<br>np.trace(arr1)<br># 15<br><br>arr3 = np.identity(3)<br>np.linalg.det(arr3) # 1.0</pre><h3>Statistical Operations</h3><p><strong>Statistical operations</strong> in NumPy provide functions for computing various descriptive statistics from arrays, such as mean, median, standard deviation, variance, minimum, maximum, and more. These operations operate either on the entire array or along a specified axis. Here are some key statistical operations in NumPy:</p><ol><li>Sum: np.sum(a)</li><li>Mean: np.mean(a)</li><li>Median: np.median(a, axis=None)</li><li>Minimum: np.min(a)</li><li>Maximum: np.max(a)</li><li>Standard deviation: np.std(a)</li><li>Variance: np.var(a)</li><li>Cumulative sum: np.cumsum(a, axis=None)</li></ol><p>These operations accept NumPy arrays as input and return scalar values or arrays containing the computed statistics.</p><p>Example:</p><pre>arr1 = np.arange(1, 10, dtype=int).reshape((3,3))<br># arr1:<br># [[1 2 3]<br>#  [4 5 6]<br>#  [7 8 9]]<br><br>np.sum(arr1) # 45<br>np.sum(arr1, axis=1) # [12 15 18] - sum of columns<br>np.median(arr1) # 5.0<br>np.max(arr1) # 9<br><br>np.min(arr1, axis=1) # [1 4 7]</pre><h3>Universal Functions</h3><p>In NumPy, <a href="https://numpy.org/doc/stable/reference/ufuncs.html"><strong>universal functions (ufuncs)</strong></a> are used for performing efficient, element-wise operations on arrays. We have already discussed some of these in above sections. <strong>ufuncs</strong> are essentially just mathematical operations that can be used to perform the operation across the array. Some common ones are: np.sin(), np.sqrt(), np.exp(), np.log(), np.max().</p><h3>Array manipulation</h3><p>NumPy offers various <strong>Array manipulation</strong> functions and operations that allow to modify the shape, structure, and content of arrays. These operations enable us to reshape, concatenate, split, stack, and transpose arrays, among other tasks. Here are some key array manipulation functions in NumPy:</p><ol><li>Transpose: a.T</li><li>Reshape: a.reshape(new_shape)</li><li>Flattening Arrays: a.flatten() - Flattens the array &#39;a&#39; into a 1-D array</li><li>Concatenation: np.concatenate((a, b), axis=0) for arrays a and b</li><li>Copying Arrays: np.copy(a)</li><li>Splitting Arrays: np.split(a, indices_or_sections, axis=0) - Splits an array into multiple sub-arrays along the specified axis</li></ol><p>These are few examples of Array manipulation functions provided in NumPy.</p><p>Example:</p><pre>arr1 = np.arange(1, 10, dtype=int).reshape((3,3))<br>arr2 = np.arange(10, 19, dtype=int).reshape((3,3))<br>arr1.flatten() # [1 2 3 4 5 6 7 8 9]<br>arr1.reshape((9, 1))<br>arr1.T</pre><p>In next blog, we will discuss Array Manipulation in details.</p><h3>Reference</h3><ul><li><a href="https://numpy.org/doc/stable/reference/routines.math.html">https://numpy.org/doc/stable/reference/routines.math.html</a></li><li><a href="https://numpy.org/doc/stable/reference/routines.linalg.html">https://numpy.org/doc/stable/reference/routines.linalg.html</a></li><li><a href="https://numpy.org/devdocs/user/quickstart.html#basic-operations">https://numpy.org/devdocs/user/quickstart.html#basic-operations</a></li><li><a href="https://numpy.org/doc/stable/user/basics.broadcasting.html">https://numpy.org/doc/stable/user/basics.broadcasting.html</a></li></ul><blockquote>Next <a href="https://medium.com/@aamernabi/numpy-array-manipulation-5f83fb111958">Array Manipulation</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c996613800cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into NumPy arrays]]></title>
            <link>https://medium.com/@aamernabi/a-deep-dive-into-numpy-arrays-77753e3a8bf5?source=rss-c9a52e47b81f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77753e3a8bf5</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aamer Paul]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 11:56:23 GMT</pubDate>
            <atom:updated>2024-03-09T13:41:23.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UJJJ0voK9cGnTEkn" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s data-driven era, where everything from scientific research to machine learning models relies heavily on numerical computations, having a suite of high-performance computing libraries is essential. NumPy, short for Numerical Python, stands out as one of the fundamental libraries for numerical computing in Python. In this series, we will get on a journey to explore the capabilities and functionalities of NumPy, uncovering its tools for array manipulation, mathematical operations, and data analysis.</p><h3><strong>What is NumPy?</strong></h3><p>NumPy is a powerful Python library for numerical computing that provides support for arrays, matrices, and a wide range of mathematical functions to operate on data structures efficiently. NumPy’s main object is the <strong>homogeneous </strong>multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers.</p><h3>Getting started</h3><p>Before getting started, make sure you are using Python v3.+ on your machine. To get started we need to first install the numpy. We can do so by running following command.</p><pre>pip install numpy</pre><p>After installing the numpy, we can import and use the numpy.</p><pre>import numpy as np<br><br>arr = np.array([1, 2, 3]) <br>print(arr) # [1 2 3]</pre><p>Here we created the numpy array with one dimension. In numpy dimensions are called <strong>axes</strong>. The array arr has one axis and this axis has 3 elements in it, so we say it has a length of 3.</p><p>We can create multi-dimension arrays in numpy. In the following example, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3. The data type of this array is float64 .</p><pre>arr = np.array(<br>    [[2., 0., 1.],<br>     [3., 0., 2.]]<br>)</pre><p>NumPy’s array class is called <strong>ndarray</strong>. Following are the important attributes of an <strong>ndarray</strong> object:</p><ul><li><strong>ndim</strong> the number of axes (dimensions) of the array.</li><li><strong>shape</strong> the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with <em>n</em> rows and <em>m</em> columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.</li><li><strong>size</strong> the total number of elements of the array. This is equal to the product of the elements of shape <em>(n * m)</em>.</li><li><strong>dtype</strong> an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int8, numpy.int16, numpy.int32, and numpy.float64 are some examples.</li><li><strong>itemsize</strong> the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.</li><li><strong>data</strong> the buffer containing the actual elements of the array. We don’t usually use this attribute because we access the elements in an array using indexing facilities.</li></ul><p><strong>Example:</strong></p><pre>import numpy as np<br><br><br>arr = np.array([<br> [ 1,  2,  3,  4, 5],<br> [ 6,  7,  8,  9, 10],<br> [11, 12, 13, 14, 15],<br> [16, 17, 18, 19, 20],<br>])<br><br>print(type(arr)) # &lt;class &#39;numpy.ndarray&#39;&gt;<br>print(&quot;ndim:&quot;, arr.ndim) # ndim: 2<br>print(&quot;shape:&quot;, arr.shape) # shape: (4, 5)<br>print(&quot;size:&quot;, arr.size) # size: 20<br>print(&quot;dtype.name:&quot;, arr.dtype.name) # dtype.name: int64<br>print(&quot;itemsize:&quot;, arr.itemsize) # itemsize: 8<br>print(&quot;total itemsize: &quot;, arr.size * arr.itemsize) # total itemsize: 160<br># or use `arr.nbytes` instead of `arr.size * arr.itemsize`<br>print(&quot;data:&quot;, arr.data) # &lt;memory at 0x7f2d........&gt;<br><br>print(np.array([1, 2], dtype=&quot;int8&quot;).itemsize) # itemsize will be 1 byte</pre><h3>Array Creation</h3><p>There are several ways to create an array in numpy.</p><p>For Example, np.array([1, 2, 3]) creates an ndarray of shape=(3,), anddtype=int64. Default integer data type is int64.</p><p>Similarly, np.array([[ 0.1, 0.2, 0.3], [ 0.4, 0.5, 0.6]]) creates an ndarray of shape=(2, 3), anddtype=float64.</p><p>If we mix the types, numpy will default to the data type that can accommodate all the elements while maintaining the highest precision possible. For example,</p><pre>arr = np.array([(1, 2.9, 3), (4, 5, 6)])<br>print(arr.dtype) # float64<br>print(arr)<br>#  [[1.  2.9 3. ]<br>#   [4.  5.  6. ]]</pre><p>We can also explicitly specify the type at creation time:</p><pre>arr = np.array([[1, 2], [3, 4]], dtype=complex) <br>print(arr.dtype) # complex128</pre><p>There are scenarios when the elements of an array are unknown initially, but its size is known. NumPy offers several functions to create arrays with initial placeholder content. For example,</p><ul><li><strong>zeros</strong> creates an array full of zeros.</li><li><strong>ones</strong> creates an array full of ones.</li><li><strong>empty</strong> creates an array whose initial content is random and depends on the state of the memory. The default dtype of the created array is float64.</li><li><strong>full</strong> creates an array full of specified value.</li><li><strong>identity</strong> creates an identity array. The identity array is a square array with ones on the main diagonal.</li><li><strong>arange</strong> creates an array with sequences of numbers. (analogous to python range but creates array)</li></ul><p>The zeros, ones, and empty functions expects the following arguments, (<strong>shape</strong>, <strong>dtype</strong>, <strong>order</strong> ).</p><ol><li>The shape is the primary argument (positional arg) for specifying the shape of the output array. It can be a single integer or a tuple of integers representing the dimensions of the array along each axis.</li><li>The dtype argument specifies the data type of the elements in the array. If not provided, it defaults to numpy.float64 for numpy.ones() and numpy.zeros(), and it&#39;s unspecified for numpy.empty(), in which case the behavior is platform-dependent.</li><li>The order (optional) argument specifies the memory layout of the array. Default is C, meaning row-major. Alternative option is F for column-major. We will discuss this in later series.</li></ol><pre>np.zeros((3, 4))<br>np.ones((3,3)) <br>np.empty((5,2))<br>np.empty((2,2), dtype=&quot;int16&quot;, order=&#39;C&#39;)<br>np.full((3,3), 12)<br>np.identity(3) </pre><p>The <strong>arange()</strong> function creates an array of evenly spaced values within a specified range. Following are the arguments of arange function:</p><ol><li><strong>start</strong>: The starting value of the sequence (<strong>inclusive</strong>). If not specified, defaults to 0.</li><li><strong>stop</strong>: The end value of the sequence (<strong>exclusive</strong>).</li><li><strong>step</strong>: The step size between each pair of consecutive values. Defaults to 1 if not specified.</li><li><strong>dtype</strong>: The data type of the output array. If not specified, the data type is inferred from other input arguments.</li><li><strong>like (</strong>Optional): It allows specifying the output array&#39;s behavior in terms of type casting. If specified, the behavior follows the type of the specified array_like object or casting method.</li></ol><p>Due to the finite precision of floating-point numbers, there can be slight inaccuracies in the representation of the numbers, when using the arange function with floating point numbers. This can lead to unexpected results, especially when the step size is very small or when the start and stop values are not multiples of the step size.</p><p>To avoid such issues, it’s recommended to use the <strong>linspace()</strong> function instead that receives as an argument the number of elements that we want. For example,</p><pre># Using arange<br>c1 = np.arange(0, 1, 0.1)<br>print(c1) # [0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,]<br>print(len(c1)) # 10<br><br># Using linspace()<br>c2 = np.linspace(0, 1, 11)  # 11 elements evenly spaced between 0 and 1<br>print(c2) # [0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]<br>print(len(c2)) # 11</pre><p>In the example above:</p><ul><li>With arange(), we specify a start of 0, stop of 1, and step of 0.1.Numpy Operations However, due to floating-point precision limitations, the end value of 1 is not included in the sequence, resulting in 10 elements instead of 11.</li><li>With linspace(), we specify the start of 0, stop of 1, and the number of elements as 11. It evenly divides the interval [0, 1] into 11 segments, resulting in 11 elements in the sequence as expected.</li></ul><p>Some more array creation function that are available, but we will not discuss them in this post:Numpy Operations<br>zeros_like, ones_like, empty_like, random.Generator.random, random.Generator.normal, fromfunction, fromfile.</p><h3>Printing Array</h3><p>When printing the NumPy array, following rules are applied:</p><ol><li><strong>Last axis (rightmost axis)</strong>: Elements along the last axis are printed from left to right. This means that when you print an array, you’ll see the elements along the rightmost axis displayed horizontally, moving from left to right.</li><li><strong>Second-to-last axis</strong>: After printing the elements of the last axis, NumPy moves to the second-to-last axis. Elements along this axis are printed from top to bottom.</li><li><strong>Rest of the axes</strong>: After printing the elements of the second-to-last axis, NumPy proceeds to print the elements of the remaining axes. Similar to the second-to-last axis, elements along these axes are printed from top to bottom with each slice separated from the next by an empty line.</li></ol><pre>arr = np.arange(1, 25).reshape(2, 3, 4)<br>print(arr)<br># [[[ 1  2  3  4]<br>#  [ 5  6  7  8]<br>#  [ 9 10 11 12]]<br>#<br># [[13 14 15 16]<br>#  [17 18 19 20]<br>#  [21 22 23 24]]]</pre><p>As you can see in above example, the elements of arr array are displayed according to the rules mentioned above. You can see the elements of the last axis (size 4) printed horizontally from left to right, then the elements along the second-to-last axis (size 3) printed vertically, and each &quot;slice&quot; of the array separated by an empty line.</p><h3>Accessing Elements</h3><p>Accessing elements in a NumPy array involves indexing and slicing.</p><ol><li><strong>Indexing</strong>: We can access individual elements of a NumPy array by specifying the indices of the element along each axis. Negative indices can be used to index from the end of the array. -1 refers to the last element, -2 refers to the second-last element, and so on.</li><li><strong>Slicing: </strong>Slicing allows you to extract a portion of the array by specifying a range of indices along each axis. The basic syntax for slicing is array[start:stop:step]. If start is not provided, it defaults to 0. If stop is not provided, it defaults to the end of the array. If step is not provided, it defaults to 1. Slicing is inclusive of the start index and exclusive of the stop index. Negative indices can be used for slicing, similar to indexing.</li></ol><pre>arr = np.arange(1, 25).reshape(2, 3, 4)<br># get specific element<br>arr[0, 1, 2]<br># get specific row <br>arr[0, 1, :] # or arr[0, 1]<br># get specific coulmn<br>arr[0, :, 2]<br><br># get specific row with specific step<br>arr2 = np.arange(1, 71).reshape(2, 5, 7)<br>arr2[0, :, 0:6:2] # (Slicing)</pre><p>Some other indexing techniques are:</p><ol><li><strong>Fancy Indexing</strong>: Allows us to access multiple elements of an array by passing an array or list of indices. We can use arrays of integers or boolean arrays to index into arrays.</li><li><strong>Boolean indexing</strong>: Allows us to select elements based on a boolean condition. We can pass an array of boolean values with the same shape as the array being indexed to select elements where the corresponding value is True. Boolean Indexing can be useful in assignments as shown in example.</li><li><strong>Integer Array Indexing</strong>: Allows us to select elements using arrays of integers. The integers represent the indices of the elements to be selected along each axis.</li></ol><pre># Fancy Indexing<br>arr2 = np.arange(1, 71).reshape(2, 5, 7)<br>indices = np.array([0, 2, 4])<br>arr[:, :, indices]  # Access all rows but only columns at indices 0, 2, 4<br><br># Boolean Indexing<br>condition = arr2 &gt; 50 <br>print(arr[condition])<br>#[51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70]<br><br># Boolean Indexing in assignments<br>arr3 = np.arange(1, 10).reshape(3, 3)<br>print(arr3)<br># [[1 2 3]<br>#  [4 5 6]<br>#  [7 8 9]]<br><br>b_index = arr3 &gt; 4<br>print(arr3[b_index]) # [5 6 7 8 9] <br><br>arr3[b_index] = -1<br>print(arr3)<br># [[ 1  2  3]<br>#  [ 4 -1 -1]<br>#  [-1 -1 -1]]<br><br># Integer Array Indexing<br>row_indices = np.array([0, 2, 4])<br>col_indices = np.array([1, 3, 4])<br>print(arr2[0, row_indices, col_indices])</pre><p>In above example <em># Integer Array Indexing,</em> we are accessing the elements of 1st axis (arr2[0 …]).</p><p>row_indices = np.array([0, 2, 4]): creates a NumPy array row_indices containing the row 0, 2, and 4. If we print d2[0, row_indices]), we will get:</p><pre>[[ 1  2  3  4  5  6  7]<br> [15 16 17 18 19 20 21]<br> [29 30 31 32 33 34 35]]</pre><p>col_indices = np.array([1, 3, 4]): creates a NumPy array col_indices containing the column indices 1, 3 and 4. If we print d2[0, :, col_indices], we will get:</p><pre>[[ 2  9 16 23 30]<br> [ 4 11 18 25 32]<br> [ 5 12 19 26 33]]</pre><h3>Copies and views</h3><p>The NumPy array is a data structure consisting of two parts: the contiguous data buffer with the actual data elements and the metadata that contains information about the data buffer. The metadata includes data type, strides, and other important information.</p><h4>Views</h4><p>A view is a way of looking at the same underlying data as an existing array. It shares the same memory as the original array, but with potentially different metadata like shape, strides, and offsets. We create a view using one of the following:</p><ul><li>Slicing an array: arr_view = arr[1:3] creates a view of elements 1 to 2 (excluding 3).</li><li>Using <strong>view()</strong> method: arr_view = arr.view(dtype=complex) creates a view with a different data type.</li></ul><p>Changes made to a view <strong>affect the original array</strong>, and vice versa, as they point to the same data.</p><h4><strong>Copies</strong></h4><p>A copy is a completely new array with its own independent memory, containing the same data as the original array. We can create a copy using following:</p><ul><li><strong>copy()</strong> method: arr_copy = arr.copy().</li></ul><p>Changes made to a copy <strong>do not affect the original array</strong>, and vice versa.</p><p>We can check if an array is a view or copy by using the <strong>base </strong>attribute. arr.base = None indicates a copy, while arr.base = [original_array] indicates a view.</p><p><em>Note: Simple assignments does not create a copy.</em></p><pre>arr1 = np.zeros((2, 2), dtype=int)<br>print(arr1)<br># [[0 0]<br>#  [0 0]]<br><br># arr1 and arr2 are pointing to same ndarray object.<br>arr2 = arr1 <br>arr2[0, 0] = 100<br><br>print(arr1) # changes made to arr2 will reflect in arr1.<br># [[100   0]<br>#  [  0   0]]<br><br>print(arr2 is arr1) # True</pre><h3>Wrap up</h3><p>In this post, we learned how to install NumPy and get started with it. We explored different ways to create and manipulate arrays, discovering how powerful NumPy is for handling numbers.</p><p><em>I hope you find this post is useful!</em></p><blockquote>Next: <a href="https://medium.com/@aamernabi/numpy-operations-c996613800cc">Numpy Operations</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77753e3a8bf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>