<?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 KavyaPabba on Medium]]></title>
        <description><![CDATA[Stories by KavyaPabba on Medium]]></description>
        <link>https://medium.com/@pabbakavya123?source=rss-42be1b09893e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tAkXzU2ejya4TvQFd-N0oA.png</url>
            <title>Stories by KavyaPabba on Medium</title>
            <link>https://medium.com/@pabbakavya123?source=rss-42be1b09893e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:11:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pabbakavya123/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[Web Scraping — A Beginner’s Guide]]></title>
            <link>https://medium.com/@pabbakavya123/web-scraping-a-beginners-guide-8fe34946ce4a?source=rss-42be1b09893e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fe34946ce4a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-webscraping]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[KavyaPabba]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 00:21:23 GMT</pubDate>
            <atom:updated>2025-09-10T00:21:23.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web Scraping — A Beginner’s Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hWh_GMOcqPSNVevE" /><figcaption>Photo by <a href="https://unsplash.com/@uns__nstudio?utm_source=medium&amp;utm_medium=referral">Unseen Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Web scraping involves fetching a webpage, extracting useful data, and storing it for analysis. Instead of manually copying and pasting data, we can automate the process using Python.</p><p>However, using web scraping necessitates a <strong>basic understanding of HTML structure</strong>:</p><ul><li><strong>Tags</strong> (e.g., &lt;h1&gt;, &lt;p&gt;, &lt;a&gt;)</li><li><strong>Attributes</strong> (class, id, etc.)</li><li><strong>Nested structure</strong> (parents, children, siblings in the HTML tree)</li></ul><h3>Why Use Web Scraping?</h3><p>It is widely used for:</p><ol><li>Collecting data for <strong>research</strong> or <strong>business intelligence</strong></li><li>Monitoring prices on <strong>e-commerce websites</strong></li><li>Gathering <strong>news, sports, or financial data</strong></li><li>Automating repetitive <strong>web-based tasks</strong></li></ol><h3>How Web Scraping Works (Flow)</h3><ol><li>Send an <strong>HTTP request</strong> to a webpage.</li><li>Receive the <strong>HTML response</strong>.</li><li>Parse the HTML using <strong>BeautifulSoup</strong>.</li><li><strong>Extract the required data</strong> (text, links, tables, etc.).</li><li><strong>Save the data</strong> into CSV, Excel, or a database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTPm8JorhOug_BBiApPW0A.png" /></figure><h3>Step 1: Setting Up Your Environment</h3><p>Before we start scraping, you need to install the necessary Python libraries.</p><h4>Key Libraries for Web Scraping in Python</h4><p>To perform web scraping, you need:</p><ul><li><strong>Requests</strong> — To send HTTP requests and retrieve webpage content.</li><li><strong>BeautifulSoup</strong> — To parse and extract information from HTML.</li><li><strong>pandas — </strong>Stores scraped data in a structured format (optional but useful).</li><li><strong>sqlite3 —</strong> used for creating the database instance.</li></ul><p>Although Python 3 comes with requests and sqlite3, you still need to install the pandas and beautifulsoup libraries in the IDE.</p><h3>Installing the Libraries</h3><p>Run the following command in your terminal:</p><pre>python3.11 -m pip install pandas<br>python3.11 -m pip install bs4</pre><h3>Step 2: Import and Initialize</h3><p>Importing the relevant libraries</p><pre>import requests<br>import sqlite3<br>import pandas as pd<br>from bs4 import BeautifulSoup<br><br>url = &quot;https://example.com&quot;<br>headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0&quot;}  # Mimics a real browser request</pre><h3>Step 3: Fetch HTML Content with Python</h3><pre>try:<br>    response = requests.get(url, headers=headers, timeout=10)<br><br>    if response.status_code == 200:<br>        response_html = response.text<br>        print(response_html)  # HTML content of the page<br>    else:<br>        print(f&quot;Failed to retrieve the page. Status code: {response.status_code}&quot;)<br><br>except requests.exceptions.RequestException as e:<br>    print(f&quot;Error: {e}&quot;)</pre><h3>Explanation:</h3><ul><li>requests.get(url, headers=headers): Sends a request to the website.</li><li>headers: Some websites block scrapers, so setting a <strong>User-Agent</strong> helps mimic a browser.</li><li>response.text: Prints the raw HTML content of the page.</li></ul><h3>Step 4: Parsing HTML with BeautifulSoup</h3><pre>soup = BeautifulSoup(response.text, &quot;html.parser&quot;)<br>print(soup.prettify())  # Nicely formatted HTML</pre><h3>How to Inspect a Web Page?</h3><ol><li>Right-click on a webpage → <em>Inspect</em> (Chrome) or <em>Inspect Element</em> (Firefox).</li><li>Use the <strong>Elements tab</strong> to explore the HTML structure.</li><li>Identify the <strong>tags</strong> (&lt;h1&gt;, &lt;p&gt;, &lt;div&gt;, &lt;span&gt;) and <strong>classes/IDs</strong> where data lives.</li></ol><h3>Step 5: Extract Data from HTML</h3><h4>Extracting Headlines</h4><pre>headlines = soup.find_all(&quot;h2&quot;, class_=&quot;headline&quot;)<br>for h in headlines:<br>    print(h.text.strip())</pre><h4>Extracting Links</h4><pre>links = soup.find_all(&quot;a&quot;)<br>for link in links:<br>    print(link.get(&quot;href&quot;))</pre><h3>Step 6: Storing Data</h3><h4>Save to CSV with pandas</h4><pre>data = {&quot;Headline&quot;: [h.text.strip() for h in headlines]}<br>df = pd.DataFrame(data)<br>df.to_csv(&quot;scraped_headlines.csv&quot;, index=False)<br>print(&quot;Data saved successfully!&quot;)</pre><h3>Save to SQLite Database</h3><pre>conn = sqlite3.connect(&quot;scraped_data.db&quot;)<br>cursor = conn.cursor()<br><br>cursor.execute(&quot;CREATE TABLE IF NOT EXISTS headlines (title TEXT)&quot;)<br>for h in headlines:<br>    cursor.execute(&quot;INSERT INTO headlines VALUES (?)&quot;, (h.text.strip(),))<br><br>conn.commit()<br>conn.close()<br>print(&quot;Data saved to SQLite database!&quot;)</pre><h3>Step 7: Handling Anti-Scraping Measures</h3><ol><li><strong>Use Headers to Mimic a Browser</strong></li></ol><pre>headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0&quot;}<br>response = requests.get(url, headers=headers)</pre><p><strong>2. Add Delays Between Requests</strong></p><pre>import time<br><br>for i in range(5):<br>    response = requests.get(url, headers=headers)<br>    print(f&quot;Scraped {i+1} times&quot;)<br>    time.sleep(2)  # Wait before next request</pre><p><strong>3. Rotate IPs and User-Agents</strong></p><ul><li>Use <strong>proxy servers</strong></li><li>Use libraries like <strong>fake_useragent</strong></li><li>Use services like <strong>ScraperAPI</strong> or <strong>BrightData</strong> for scale</li></ul><h3>Step 8: Scraping a Real Website (Quotes Example)</h3><pre>url = &quot;http://quotes.toscrape.com&quot;<br>headers = {&quot;User-Agent&quot;: &quot;Mozilla/5.0&quot;}<br>response = requests.get(url, headers=headers)<br><br>if response.status_code == 200:<br>    soup = BeautifulSoup(response.text, &quot;html.parser&quot;)<br><br>    quotes = soup.find_all(&quot;span&quot;, class_=&quot;text&quot;)<br>    authors = soup.find_all(&quot;small&quot;, class_=&quot;author&quot;)<br><br>    data = {<br>        &quot;Quote&quot;: [q.text.strip() for q in quotes],<br>        &quot;Author&quot;: [a.text.strip() for a in authors]<br>    }<br><br>    df = pd.DataFrame(data)<br>    df.to_csv(&quot;quotes.csv&quot;, index=False)<br>    print(&quot;Quotes scraped and saved successfully!&quot;)<br>else:<br>    print(f&quot;Failed to access the site. Status code: {response.status_code}&quot;)</pre><h3>Step 9: Next Steps to Advance Your Skills</h3><p>✔ Scrape <strong>dynamic sites</strong> with Selenium/Puppeteer</p><p>✔ Learn <strong>Scrapy</strong> for large-scale scraping</p><p>✔ Use <strong>APIs</strong> when available (faster &amp; cleaner)</p><p>✔ Clean scraped text (strip(), regex) before saving</p><p>✔ Analyze data with <strong>pandas + Matplotlib/Seaborn</strong></p><h3>Conclusion</h3><p>Web scraping is a powerful way to automate data collection.</p><p>With <strong>Requests, BeautifulSoup, pandas, and sqlite3</strong>, you can:</p><ol><li>Fetch web pages</li><li>Parse HTML</li><li>Extract structured information</li><li>Save it into CSV or a database</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fe34946ce4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Insider Secrets I Wish I Knew Before My First Data Analyst Job]]></title>
            <link>https://medium.com/@pabbakavya123/5-insider-secrets-i-wish-i-knew-before-my-first-data-analyst-job-6aff677d6ba5?source=rss-42be1b09893e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aff677d6ba5</guid>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[first-job]]></category>
            <category><![CDATA[trends]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[KavyaPabba]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 13:38:54 GMT</pubDate>
            <atom:updated>2024-06-18T13:38:54.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nNWa6JoTCYjdK-Dm" /></figure><p>Starting your first job as a data analyst can be both exciting and a little intimidating. The thrill of diving into data, finding cool insights, and helping make big decisions is amazing.</p><p>But, just like any new adventure, there are a few things I wish I had known beforehand. Here are five insider secrets that I learned during my 2 years of experience.</p><h3>1. Understand the Business Inside Out</h3><p>When I first started, I was all about the numbers and cool charts. But I quickly learned that knowing the business side of things is just as important.</p><p>Understanding the company’s goals, what different departments do, and the specific problems they’re trying to solve makes your work much more relevant, which in turn helps bring out the results that align with your company’s goals in a much shorter duration of time.</p><p>Asking lots of questions was something I always hesitated to do. However, I slowly realised that the more questions you ask, the less time you waste, and the faster you can finish a project.</p><p>Spend time talking to people from different departments, attend meetings. The more you know about the business, the better your analysis will be.</p><h3>2. 80% of Your Time Will Be Spent Cleaning Data</h3><p>I thought I’d spend my days building fancy models and creating stunning visualizations. The reality? I spent most of my time cleaning messy data — dealing with missing values, fixing errors, and getting everything in order.</p><p>Get good at data cleaning. Learn the tools and tricks to make this process faster and more efficient. It’s not glamorous, but it’s crucial.</p><p>Get good at data cleaning by diving into the right tools and techniques. Start with learning Excel functions like VLOOKUP and pivot tables, and then move on to more powerful tools like Python and its libraries, such as Pandas.</p><p>A great trick is to use Python’s Pandas library to automate repetitive cleaning tasks. For example, writing a script to handle missing values, standardize formats, and remove duplicates can save you tons of time and effort. Practicing with real-world datasets from sites like Kaggle can also help you get a feel for the common issues you’ll face and how to tackle them efficiently.</p><h3>3. People Won’t Always Like What You Find</h3><p>One thing that surprised me was how often people didn’t like my results. Sometimes, your findings won’t match what people expected or hoped for, which can lead to some tough conversations.</p><p>People always ask for data-driven solutions, but they’re not always happy if the results aren’t positive which they generally aren’t. To handle this, always back up your analysis with solid evidence. Having 2 or 3 alternative solutions ready can also work in your favor, providing options that can help address concerns and find a path forward.</p><h3>4. You’ll Always Be Learning</h3><p>Data analytics is a field that’s always changing. New tools, techniques, and technologies are constantly popping up. I quickly realized that my formal education was just the beginning and that real-world data projects are a whole different ball game.</p><p>Working with live datasets is much tougher than dealing with the neat, curated datasets you use during courses. Real-life data is messy, incomplete, and full of surprises. You’ll encounter missing values, inconsistencies, and unexpected outliers that require creative solutions. This is where your problem-solving skills truly get tested.</p><p>It’s not enough to know just one software or tool. New challenges pop up every day, and you’ll need to be versatile and adaptable.</p><p>For instance, right after starting my first job, I had to learn new software tools that I hadn’t encountered before. This cycle of learning never ends, so be prepared to solve new problems and learn new tools constantly.</p><h3>6. Real-Life Situations Don’t Always Align with Data</h3><p>One of the most challenging aspects of being a data analyst is recognizing that real-life situations don’t always align perfectly with what the data predicts. For example, your analysis might show that sales will decline if prices aren’t reduced. However, this might not happen due to factors like seasonal trends, weather conditions, competitive actions, or regional differences. These real-world variables can significantly impact the outcomes.</p><p>Always be prepared to contextualize your data findings. Support your arguments with historical data and consider external factors that might influence the results. For instance, if your data suggests a potential drop in sales, look at past years to see if similar patterns occurred due to specific events like holidays, weather changes, or competitive moves</p><p>By combining solid data analysis with real-world considerations, you’ll offer more robust and practical solutions that can better address the complexities of business realities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aff677d6ba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Hidden Patterns: The Power of Clustering Analysis in Data Exploration(EDA).]]></title>
            <link>https://medium.com/@pabbakavya123/unveiling-hidden-patterns-the-power-of-clustering-analysis-in-data-exploration-a72617abde55?source=rss-42be1b09893e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a72617abde55</guid>
            <category><![CDATA[clustering-algorithm]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-exploration]]></category>
            <dc:creator><![CDATA[KavyaPabba]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 22:41:15 GMT</pubDate>
            <atom:updated>2023-08-05T18:40:17.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_Xo8U_cLzpVbLFW0BXfuA.jpeg" /></figure><h3>The Power of Clustering: Grouping Similar Entities</h3><p>Clustering is an unsupervised machine learning technique that involves grouping similar data points together based on their similarities. The goal of clustering is to discover patterns or structures within the data without any predefined labels or categories. It is commonly used in data analysis, pattern recognition, and data mining to identify natural groupings in the data.</p><h4>The Process of Clustering:</h4><ol><li>Data Collection.</li><li>Data Preprocessing.</li><li>Choosing a Clustering Algorithm.</li><li>Feature Selection (Optional).</li><li>Applying the Clustering Algorithm.</li><li>Evaluating Clustering Results.</li><li>Interpretation and Visualization.</li><li>Applying Clustering to New Data (Prediction).</li></ol><h3>Types of Clustering Algorithms:</h3><h4>a. Partition- based Clustering:</h4><p>Partition-based clustering is a type of clustering algorithm that divides data points into non-overlapping clusters. The goal is to group similar data points together while maximizing the homogeneity within each cluster and maximizing the heterogeneity between different clusters. The most well-known and widely used partition-based clustering algorithm is the k-means algorithm.</p><p>K-Means Algorithm: The k-means algorithm is an iterative, partition-based clustering algorithm that aims to partition ’n’ data points into ‘k’ clusters, where ‘k’ is a user-specified parameter. The steps of the k-means algorithm are as follows:</p><ul><li>Import Libraries:</li></ul><pre>import pandas as pd<br>import numpy as np<br>from sklearn.cluster import KMeans<br>import matplotlib.pyplot as plt</pre><ul><li>Load Data:</li></ul><pre># Load data into DataFrame (replace &#39;data.csv&#39; with your dataset file)<br>df = pd.read_csv(&#39;data.csv&#39;)</pre><ul><li>Choose the Number of Clusters (k): Decide on the number of clusters you want to create. This can be based on domain knowledge or using techniques like the elbow method or silhouette score to determine the optimal value for ‘k.’</li></ul><pre># Choose the number of clusters (k)<br>k = 3</pre><ul><li>Prepare Data for Clustering:</li></ul><pre>X = df[[&#39;Feature1&#39;, &#39;Feature2&#39;, ...]]  # Replace &#39;Feature1&#39;, &#39;Feature2&#39;, ... with the relevant feature names</pre><ul><li>Perform K-Means Clustering:</li></ul><pre>kmeans = KMeans(n_clusters=k, random_state=42)  # Initialize the k-means object with the chosen number of clusters<br>kmeans.fit(X)  # Perform clustering on the data</pre><ul><li>Retrieve Cluster Assignments and Centroids:</li></ul><pre># Cluster assignments for each data point<br>df[&#39;Cluster&#39;] = kmeans.labels_<br><br># Cluster centroids<br>centroids = kmeans.cluster_centers_</pre><ul><li>Visualize Clusters (Optional):</li></ul><pre># Plot data points colored by cluster<br>plt.scatter(X[&#39;Feature1&#39;], X[&#39;Feature2&#39;], c=kmeans.labels_, cmap=&#39;rainbow&#39;)<br># Plot cluster centroids<br>plt.scatter(centroids[:, 0], centroids[:, 1], marker=&#39;X&#39;, s=100, c=&#39;black&#39;, label=&#39;Centroids&#39;)<br>plt.legend()<br>plt.xlabel(&#39;Feature1&#39;)<br>plt.ylabel(&#39;Feature2&#39;)<br>plt.title(&#39;K-Means Clustering&#39;)<br>plt.show()</pre><h4>b. Hierarchical clustering:</h4><p>Hierarchical clustering builds a tree-like structure of nested clusters, known as a dendrogram. There are two main types of hierarchical clustering:</p><ul><li>Agglomerative: Starts with each data point as its own cluster and successively merges the closest clusters until reaching a single cluster that includes all data points.</li><li>Divisive: Starts with all data points in one cluster and recursively divides the clusters until each data point is in its own cluster.</li></ul><p>To perform hierarchical clustering using Python and the scipy library, follow these steps:</p><ul><li>Import Libraries:</li></ul><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from scipy.cluster.hierarchy import linkage, dendrogram</pre><ul><li>Prepare Data for Clustering:</li></ul><pre>X = df[[&#39;Feature1&#39;, &#39;Feature2&#39;, ...]]  # Replace &#39;Feature1&#39;, &#39;Feature2&#39;, ... with the relevant feature names</pre><ul><li>Perform Hierarchical Clustering:</li></ul><pre># Calculate the linkage matrix using the chosen method and metric<br># Replace &#39;method&#39; with the linkage method (e.g., &#39;ward&#39;, &#39;single&#39;, &#39;complete&#39;, &#39;average&#39;, etc.)<br># Replace &#39;metric&#39; with the distance metric (e.g., &#39;euclidean&#39;, &#39;manhattan&#39;, &#39;cosine&#39;, etc.)<br>linked = linkage(X, method=&#39;ward&#39;, metric=&#39;euclidean&#39;)</pre><ul><li>Visualize the Dendrogram:</li></ul><pre># Plot the dendrogram<br>dendrogram(linked, orientation=&#39;top&#39;, distance_sort=&#39;descending&#39;, show_leaf_counts=True)<br>plt.xlabel(&#39;Data Points&#39;)<br>plt.ylabel(&#39;Distance&#39;)<br>plt.title(&#39;Hierarchical Clustering Dendrogram&#39;)<br>plt.show()</pre><ul><li>Select the Number of Clusters:</li></ul><p>Based on the dendrogram, you can choose the number of clusters by observing the vertical lines and deciding the optimal number of cuts that form meaningful clusters.</p><ul><li>Assign Cluster Labels:</li></ul><pre>from scipy.cluster.hierarchy import fcluster<br><br># Replace &#39;k&#39; with the chosen number of clusters<br>k = 3<br>clusters = fcluster(linked, k, criterion=&#39;maxclust&#39;)<br><br># Add the cluster labels to the DataFrame<br>df[&#39;Cluster&#39;] = clusters</pre><h4>c. Density-based Clustering:</h4><p>Density-based clustering algorithms identify regions of high data point density as clusters. One popular example is DBSCAN (Density-Based Spatial Clustering of Applications with Noise), which groups data points that are close to each other and have a minimum number of neighbors within a specified distance.</p><p>Import Libraries:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.cluster import DBSCAN</pre><ul><li>Load Data:</li></ul><pre># Load data into DataFrame (replace &#39;data.csv&#39; with your dataset file)<br>df = pd.read_csv(&#39;data.csv&#39;)</pre><ul><li>Prepare Data for Clustering:</li></ul><pre>X = df[[&#39;Feature1&#39;, &#39;Feature2&#39;, ...]]  # Replace &#39;Feature1&#39;, &#39;Feature2&#39;, ... with the relevant feature names</pre><ul><li>Perform Density-Based Clustering (DBSCAN):</li></ul><pre># Initialize DBSCAN with appropriate hyperparameters (eps and min_samples)<br># &#39;eps&#39; is the maximum distance between two samples to be considered in the same neighborhood<br># &#39;min_samples&#39; is the minimum number of samples required to form a core point<br>dbscan = DBSCAN(eps=0.5, min_samples=5)<br>clusters = dbscan.fit_predict(X)</pre><ul><li>Visualize Clusters (Optional):</li></ul><pre># Plot data points colored by cluster<br>plt.scatter(X[&#39;Feature1&#39;], X[&#39;Feature2&#39;], c=clusters, cmap=&#39;rainbow&#39;)<br>plt.xlabel(&#39;Feature1&#39;)<br>plt.ylabel(&#39;Feature2&#39;)<br>plt.title(&#39;DBSCAN Clustering&#39;)<br>plt.show()</pre><ul><li>Identify Noise Points (Optional):</li></ul><pre># Identify noise points (points with cluster label -1)<br>noise_points = X[clusters == -1]</pre><h4>d.Model-based Clustering:</h4><p>Model-based clustering assumes that the data is generated from a specific statistical distribution. The goal is to find the best-fitting model that describes the data distribution and assigns data points to clusters based on model parameters. An example of model-based clustering is Gaussian Mixture Model (GMM).</p><ul><li>Import Libraries:</li></ul><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.mixture import GaussianMixture</pre><ul><li>Load Data:</li></ul><pre># Load data into DataFrame (replace &#39;data.csv&#39; with your dataset file)<br>df = pd.read_csv(&#39;data.csv&#39;)</pre><ul><li>Prepare Data for Clustering:</li></ul><pre>X = df[[&#39;Feature1&#39;, &#39;Feature2&#39;, ...]]  # Replace &#39;Feature1&#39;, &#39;Feature2&#39;, ... with the relevant feature names</pre><ul><li>Perform Model-Based Clustering (GMM):</li></ul><pre># Initialize GMM with appropriate hyperparameters (n_components represents the number of clusters)<br>gmm = GaussianMixture(n_components=3)  # Replace &#39;3&#39; with the desired number of clusters<br>clusters = gmm.fit_predict(X)</pre><ul><li>Visualize Clusters (Optional):</li></ul><pre># Plot data points colored by cluster<br>plt.scatter(X[&#39;Feature1&#39;], X[&#39;Feature2&#39;], c=clusters, cmap=&#39;rainbow&#39;)<br>plt.xlabel(&#39;Feature1&#39;)<br>plt.ylabel(&#39;Feature2&#39;)<br>plt.title(&#39;GMM Clustering&#39;)<br>plt.show()</pre><ul><li>Retrieve Cluster Parameters (Optional):</li></ul><pre># Get the cluster means and covariance matrices<br>cluster_means = gmm.means_<br>cluster_covariances = gmm.covariances_</pre><h4>e. Centroid-based Clustering:</h4><p>Centroid-based clustering algorithms use a representative point (centroid) to define each cluster. Besides k-means, other examples include k-medoids (PAM) and Fuzzy C-Means (FCM) algorithm.</p><h4>f. Subspace Clustering:</h4><p>Subspace clustering aims to find clusters in specific subspaces or combinations of features. It is particularly useful when different subsets of features define distinct patterns or relationships among data points.</p><h4>g. Spectral Clustering:</h4><p>Spectral clustering transforms the data into a lower-dimensional space using eigenvalues and eigenvectors of a similarity matrix. The data points are then clustered in the lower-dimensional space using standard clustering techniques like k-means.</p><h4>h. Biclustering:</h4><p>Biclustering is a special type of clustering that simultaneously clusters both rows and columns in a dataset. It is useful for discovering patterns in data where subsets of rows and columns show similar behaviors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a72617abde55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide on Exploratory Data Analysis (EDA)]]></title>
            <link>https://medium.com/@pabbakavya123/a-comprehensive-guide-on-exploratory-data-analysis-eda-ab38f33d6abc?source=rss-42be1b09893e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab38f33d6abc</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[guidelines]]></category>
            <dc:creator><![CDATA[KavyaPabba]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 17:54:45 GMT</pubDate>
            <atom:updated>2023-07-30T17:54:45.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMRg4M0mauHBO-IDgJhN3A.png" /></figure><h3><strong>What is Exploratory Data Analysis (EDA)?</strong></h3><p>EDA is a crucial aspect of data science that helps in understanding the underlying structure of the data. It involves analyzing and summarizing data visually and statistically to uncover patterns or relationships. The main goals of EDA include:</p><ul><li>Gaining a deeper understanding of the data</li><li>Identifying data quality issues</li><li>Developing initial insights and hypotheses</li><li>Selecting features for modeling or further analysis</li></ul><h3>How to Perform Exploratory Data Analysis (EDA):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIw-OvVlU6g7In4tvFyyUw.jpeg" /></figure><h3>I. Data Collection:</h3><p>The first step in EDA is data collection. Data can come from a variety of sources, including databases, websites, APIs, and file storage services. It’s essential to ensure that the data is collected in a format that can be easily analyzed and manipulated.</p><h3>Process of Collecting Data</h3><p>To collect data, consider the following steps:</p><ol><li>Define the research question you want to answer.</li></ol><p>2. Identify the data needed to answer the question.</p><p>3. Identify potential data sources, such as databases, websites, APIs, or file. storage services.</p><p>4. Collect the data in a format that can be easily analyzed and manipulated.</p><h3>II. Importing Libraries:</h3><p>When performing exploratory data analysis (EDA), you’ll need to import several libraries to facilitate data manipulation, visualization, and analysis. Here are some commonly used libraries for EDA in Python:</p><pre>import pandas as pd   <br># For data manipulation and analysisimport numpy as np           <br># For numerical operationsimport matplotlib.pyplot as plt    <br># For basic data visualizationimport seaborn as sns       <br># For advanced data visualizationimport scipy.stats as stats  <br># For statistical analysis</pre><ul><li>pandas is a powerful library for data manipulation and analysis, providing tools to read, manipulate, and analyze structured data.</li><li>numpy is a library that provides mathematical functions for numerical operations in Python, essential for working with arrays and matrices.</li><li>matplotlib.pyplot is a plotting library used to create basic data visualizations, such as line plots, histograms, and scatter plots.</li><li>seaborn is a visualization library that provides a high-level interface for creating more advanced and aesthetically pleasing visualizations.</li><li>scipy.stats is a module from the SciPy library that provides a wide range of statistical functions and distributions.</li></ul><p>To import these libraries, include the import statements at the beginning of your Python script or Jupyter Notebook. You can then use the functionalities provided by these libraries to perform various EDA tasks, such as data manipulation, visualization, and statistical analysis.</p><p>Example:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import scipy.stats as stats    # Your code for EDA goes here</pre><p>By importing and utilizing these libraries, you’ll have the necessary tools to efficiently perform EDA on your dataset.</p><h3>III. Data Cleaning:</h3><p>Before exploring and analyzing the data through EDA, data cleaning is necessary. It involves identifying and resolving data quality issues such as missing values, outliers, and duplicates. These issues can affect the accuracy of the insights derived during EDA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMsrcN6xYIVv4SXISqikbA.jpeg" /></figure><h3>Steps in Data Cleaning</h3><p>To clean your data effectively, follow these steps:</p><h3>1. Identify and remove duplicates.</h3><p>Identifying and removing duplicates from a dataset is an essential data cleaning step to ensure data integrity and accuracy in any data analysis or machine learning project. Duplicates can arise due to data entry errors, system glitches, or other reasons, and they can skew analyses and lead to misleading results. Here’s a general outline of how to identify and remove duplicates from a dataset:</p><p>In Python (using pandas):</p><pre>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame<br><br>duplicates = df.duplicated()<br>print(df[duplicates])</pre><h3>2. Identify and deal with missing values in the data.</h3><p>Dealing with missing values is a crucial aspect of data cleaning and preprocessing, as missing data can lead to biased analysis and inaccurate results. There are various strategies to handle missing values, depending on the nature of the data and the amount of missingness. Here’s a step-by-step guide on how to identify and deal with missing values in the data:</p><pre>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame<br>print(df.isnull().sum())</pre><p>Based on the evaluation, choose an appropriate strategy to handle missing values. Some common techniques include:</p><p>a. Deletion:</p><p>If missing values are limited and randomly distributed, you may choose to remove rows or columns with missing data.</p><pre># To drop rows with any missing values<br>df_cleaned = df.dropna()<br><br># To drop columns with any missing values<br>df_cleaned = df.dropna(axis=1)</pre><p>b. Imputation:</p><p>If you have a significant amount of missing data or cannot. afford to lose entire rows or columns, impute missing values with reasonable estimates.</p><p>Common imputation methods include mean, median, mode, forward-fill, backward-fill, and regression-based imputation.</p><pre># Impute missing values with mean<br>df_cleaned = df.fillna(df.mean())<br><br># Impute missing values with forward-fill<br>df_cleaned = df.fillna(method=&#39;ffill&#39;)<br><br># Impute missing values with backward-fill<br>df_cleaned = df.fillna(method=&#39;bfill&#39;)</pre><h3>3. Address outliers by either removing or transforming them.</h3><p>Outliers are data points that deviate significantly from the rest of the data and can be caused by errors in data collection or represent extreme cases that need special consideration. Dealing with outliers can be done in two primary ways:</p><p>a. Removing Outliers:</p><p>Removing outliers involves simply eliminating data points that are considered outliers from the dataset. This method is suitable when you are confident that the outliers are due to data entry errors or are irrelevant to the analysis</p><pre>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame and &#39;column_name&#39; is the column containing outliers<br>Q1 = df[column_name].quantile(0.25)<br>Q3 = df[column_name].quantile(0.75)<br>IQR = Q3 - Q1<br><br># Filter outliers using the interquartile range (IQR) method<br>df_cleaned = df[(df[column_name] &gt;= Q1 - 1.5 * IQR) &amp; (df[column_name] &lt;= Q3 + 1.5 * IQR)]</pre><p>b. Transforming Outliers:</p><p>Instead of removing outliers, another approach is to transform the data to reduce the impact of outliers on the analysis. Common transformation techniques include log transformation, square root transformation, or Box-Cox transformation.</p><pre>import numpy as np<br>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame and &#39;column_name&#39; is the column containing outliers<br># Log transformation<br>df[&#39;transformed_column&#39;] = np.log(df[column_name])<br><br># Square root transformation<br>df[&#39;transformed_column&#39;] = np.sqrt(df[column_name])<br><br># Box-Cox transformation (requires data to be positive, so you might need to add a constant if necessary)<br>from scipy.stats import boxcox<br>df[&#39;transformed_column&#39;], _ = boxcox(df[column_name])</pre><h3>4. Remove or correct irrelevant data.</h3><p>Irrelevant data includes information that is not useful or applicable to the analysis, either due to data entry errors or because it does not align with the research question or analysis objectives.</p><p>Step 1: Identify Irrelevant Data Start by examining your dataset and identifying any data points or columns that do not contribute to the analysis or have no meaningful relevance. This could include:</p><p>a. Columns with constant values.</p><p>b. Columns with mostly missing data.</p><p>c. Data points or rows with missing values in critical fields.</p><p>Step 2: Evaluate Data Quality For data that seems potentially irrelevant, check for data quality issues, such as data entry errors, typos, or inconsistencies. Evaluate whether these issues can be corrected or if the data should be removed.</p><p>Step 3: Remove Irrelevant data once you have identified irrelevant data, you can remove it from the dataset.</p><pre>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame<br># Removing rows with missing values in critical fields<br>df_cleaned = df.dropna(subset=[&#39;critical_field&#39;])<br><br># Removing columns with constant values or high missing value percentage<br>df_cleaned = df.drop(columns=[&#39;column_with_constant_values&#39;, &#39;column_with_high_missing&#39;])</pre><h3>5. Detect and deal with any invalid or inconsistent data.</h3><p>Invalid data refers to information that does not conform to the expected format or valid range, while inconsistent data refers to contradictory or conflicting entries within the dataset.</p><p>Step 1: Identify Invalid or Inconsistent Data Start by thoroughly examining your dataset and identifying potential issues, such as:</p><p>a. Data outside valid ranges.</p><p>b. Contradictory information.</p><p>c. Format discrepancies.</p><p>d. Data type inconsistencies.</p><p>Step 2: Data Validation Perform data validation checks to verify the integrity of the data. Common validation checks include:</p><p>a. Ensure that numeric values fall within valid ranges.</p><p>b. Validate that data entries match the expected format.</p><p>c. Cross-check related fields to ensure their consistency.</p><pre>import pandas as pd<br><br># Assuming &#39;df&#39; is your DataFrame<br><br># Range checks for numeric columns<br>invalid_numeric_data = df[(df[&#39;numeric_column&#39;] &lt; lower_bound) | (df[&#39;numeric_column&#39;] &gt; upper_bound)]<br><br># Format checks for date column (assuming &#39;date_column&#39; is in &#39;datetime&#39; format)<br>invalid_date_format_data = df[~df[&#39;date_column&#39;].dt.strftime(date_format).isin(valid_date_formats)]<br><br># Consistency check for related fields<br>inconsistent_data = df[df[&#39;related_field1&#39;] != df[&#39;related_field2&#39;]]</pre><p>Step 3: Handle Invalid or Inconsistent Data The appropriate method for handling invalid or inconsistent data depends on the specific context and the nature of the errors. Options include:</p><p>a. Removal.</p><p>b. Imputation.</p><p>c. Manual Correction.</p><p>d. Data Transformation.</p><pre># Removing invalid rows<br>df_cleaned = df.drop(invalid_rows.index)<br><br># Imputing missing or invalid values in numeric columns<br>df[&#39;numeric_column&#39;].fillna(df[&#39;numeric_column&#39;].mean(), inplace=True)<br><br># Imputing missing or invalid values in categorical columns<br>df[&#39;categorical_column&#39;].fillna(df[&#39;categorical_column&#39;].mode()[0], inplace=True)</pre><h3>IV. Data Exploration:</h3><p>Exploring the data is the next step in the EDA process. It helps to identify patterns and trends and forms the basis of the data analysis phase. Common EDA techniques include the use of summary statistics, visualizations, and correlation matrices.</p><h3>Process of Exploring Data</h3><p>To explore the data effectively, follow these four steps:</p><h3>1. Calculate summary statistics such as mean, median, and mode to understand the central tendencies and distributions of the data.</h3><p>Mean: The mean, also known as the average, is calculated by summing all the values in the dataset and dividing by the number of data points.</p><pre>import pandas as pd<br>import numpy as np<br><br># Assuming &#39;df&#39; is your DataFrame, and &#39;column_name&#39; is the column for which you want to calculate the mean<br>mean_value = df[&#39;column_name&#39;].mean()<br><br># If you have a NumPy array instead of a DataFrame:<br>mean_value = np.mean(array)</pre><p>Median: The median is the middle value in a dataset when it is sorted in ascending order. If the dataset has an odd number of data points, the median is the middle value. If the dataset has an even number of data points, the median is the average of the two middle values.</p><pre># Assuming &#39;df&#39; is your DataFrame, and &#39;column_name&#39; is the column for which you want to calculate the median<br>median_value = df[&#39;column_name&#39;].median()<br><br># If you have a NumPy array instead of a DataFrame:<br>median_value = np.median(array)</pre><p>Mode: The mode is the value that appears most frequently in a dataset.</p><pre>from scipy import stats<br><br># Assuming &#39;df&#39; is your DataFrame, and &#39;column_name&#39; is the column for which you want to calculate the mode<br>mode_value = stats.mode(df[&#39;column_name&#39;])[0][0]</pre><h3>2. Visualize the data using graphs, charts, and histograms. This will help to identify any patterns or anomalies in the data.</h3><p>Scatter Plot:</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Assuming &#39;df&#39; is your DataFrame, and &#39;x_column&#39; and &#39;y_column&#39; are the columns you want to compare<br>plt.figure(figsize=(8, 6))<br>sns.scatterplot(data=df, x=&#39;x_column&#39;, y=&#39;y_column&#39;)<br>plt.xlabel(&#39;X Axis Label&#39;)<br>plt.ylabel(&#39;Y Axis Label&#39;)<br>plt.title(&#39;Scatter Plot&#39;)<br>plt.show()</pre><p>Line Chart:</p><pre># Assuming &#39;df&#39; is your DataFrame, and &#39;x_column&#39; and &#39;y_column&#39; are the columns representing time and the corresponding values<br>plt.figure(figsize=(8, 6))<br>plt.plot(df[&#39;x_column&#39;], df[&#39;y_column&#39;])<br>plt.xlabel(&#39;Time&#39;)<br>plt.ylabel(&#39;Values&#39;)<br>plt.title(&#39;Line Chart&#39;)<br>plt.show()</pre><p>Histogram:</p><pre># Assuming &#39;df&#39; is your DataFrame, and &#39;column_name&#39; is the column you want to plot a histogram for<br>plt.figure(figsize=(8, 6))<br>plt.hist(df[&#39;column_name&#39;], bins=20, edgecolor=&#39;black&#39;)<br>plt.xlabel(&#39;Values&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.title(&#39;Histogram&#39;)<br>plt.show()</pre><p>Box Plot:</p><pre># Assuming &#39;df&#39; is your DataFrame, and &#39;column_name&#39; is the column you want to plot a box plot for<br>plt.figure(figsize=(8, 6))<br>sns.boxplot(data=df, y=&#39;column_name&#39;)<br>plt.ylabel(&#39;Values&#39;)<br>plt.title(&#39;Box Plot&#39;)<br>plt.show()</pre><h3>3. Examine the correlations between variables using correlation matrices or scatter plots.</h3><p>Correlation Matrix:</p><p>A correlation matrix is a table that displays the correlation coefficients between all pairs of numeric variables in the dataset. Correlation coefficients quantify the strength and direction of the linear relationship between two variables. The values range from -1 to 1, where -1 indicates a perfect negative correlation, 1 indicates a perfect positive correlation, and 0 indicates no linear correlation.</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Assuming &#39;df&#39; is your DataFrame<br>correlation_matrix = df.corr()<br><br># Create a heatmap to visualize the correlation matrix<br>plt.figure(figsize=(10, 8))<br>sns.heatmap(correlation_matrix, annot=True, cmap=&#39;coolwarm&#39;, fmt=&quot;.2f&quot;, linewidths=0.5)<br>plt.title(&#39;Correlation Matrix&#39;)<br>plt.show()</pre><p>Scatter Plot:</p><p>A scatter plot is a graphical representation of the relationship between two continuous variables. Each data point is plotted as a point on the chart, with one variable represented on the x-axis and the other on the y-axis. Scatter plots help identify patterns and trends in the data, such as linear, non-linear, or no relationship.</p><pre>import matplotlib.pyplot as plt<br><br># Assuming &#39;df&#39; is your DataFrame, and &#39;x_column&#39; and &#39;y_column&#39; are the columns you want to compare<br>plt.figure(figsize=(8, 6))<br>plt.scatter(df[&#39;x_column&#39;], df[&#39;y_column&#39;])<br>plt.xlabel(&#39;X Axis Label&#39;)<br>plt.ylabel(&#39;Y Axis Label&#39;)<br>plt.title(&#39;Scatter Plot&#39;)<br>plt.show()</pre><h3>4. Use hypothesis tests to form initial insights and generate new hypotheses.</h3><p>Hypothesis testing is a statistical method used to make inferences about a population based on sample data. It allows you to test assumptions or claims about the population and draw conclusions from the observed data. By using hypothesis tests, you can form initial insights and generate new hypotheses, which can guide further data analysis and investigation.</p><p>a. Formulate the Null and Alternative Hypotheses.</p><p>b. Choose a Statistical Test.</p><p>c. Set the Significance Level (Alpha).</p><p>d. Calculate the Test Statistic and P-value.</p><p>e. Make a decision, draw conclusions and form New Hypotheses.</p><p>Example: Chi-square Test for Independence:</p><p>Null Hypothesis (H0): There is no association between smoking status (smoker/non-smoker) and the incidence of lung cancer.</p><p>Alternative Hypothesis (H1): There is an association between smoking status and the incidence of lung cancer.</p><p>Perform a chi-square test for independence to assess whether smoking status and the incidence of lung cancer are related. If the p-value is less than the significance level, you may reject the null hypothesis and conclude that smoking status and lung cancer incidence are associated.</p><h3>V. Data Analysis:</h3><p>The data analysis phase involves using various techniques to gain insights into the underlying structure and relationships in the data. Common techniques used include clustering, regression, and classification.</p><h3>Analyzing Data Effectively</h3><p>To analyze your data effectively, consider the following:</p><ol><li>Decide what type of analysis is appropriate for the research question.</li><li>Implement the chosen analysis technique.</li><li>Interpret the results and identify patterns and trends in the data.</li><li>Update further research questions and explore in more detail.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab38f33d6abc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>