<?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 Zainab Mehmood on Medium]]></title>
        <description><![CDATA[Stories by Zainab Mehmood on Medium]]></description>
        <link>https://medium.com/@zainab.mehmood?source=rss-8a6354b12a08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m_y55EgYBnGvcAIo_1AnIQ.jpeg</url>
            <title>Stories by Zainab Mehmood on Medium</title>
            <link>https://medium.com/@zainab.mehmood?source=rss-8a6354b12a08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:40:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zainab.mehmood/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[ML-Human-activity-recognition-of-accelerometer-data]]></title>
            <link>https://medium.com/@zainab.mehmood/ml-human-activity-recognition-of-accelerometer-data-bef1e9beaf16?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef1e9beaf16</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 11:52:56 GMT</pubDate>
            <atom:updated>2024-09-04T11:52:56.517Z</atom:updated>
            <content:encoded><![CDATA[<p>The dataset used is unique, consisting of synthetic data generated from a subset of data originally collected by the WISDM Lab (<a href="https://www.cis.fordham.edu/wisdm/">https://www.cis.fordham.edu/wisdm/</a>). This dataset is available for practice at the following GitHub link: <a href="https://github.com/ZainabMCheema/ML-Human-activity-recognition-of-accelerometer-data">ML-Human Activity Recognition of Accelerometer Data</a>.</p><p>This blog discusses the exploratory analysis of the dataset and the feature extraction process from the time series data. Various machine learning models were applied, and some of these are available on the GitHub link provided above.</p><h3><strong>Exploratory Data Analysis</strong></h3><h4>Data Pre-processing</h4><h4>Data Imbalance</h4><p>The training and test datasets were unbalanced, as Figure 1 below illustrates. Given that it is a multiclass classification problem, the six classes in the activity were plotted against the dataset. With 2452 counts, walking is the most frequent class, followed by jogging with 1951 counts. The number of values for the upstairs (702), downstairs (606), sitting (321), and standing (278) classes in the training dataset is relatively low. The test data set showed a similar trend with a different value count, with walking (768) and jogging (689) being the first and second dominant classes, respectively. The remaining classes have relatively low value counts in the data set, with the lowest value count being 22.</p><p>To deal the data imbalance, under sampling, smooth and parameter weight parameter were used during the model training. Some models like random forest, gradient boosting decision tree and CNN are not sensitive to imbalanced data set. In first phase model training imbalanced datasets converted into balanced datasets. In last phase of model training ‘Precision/’Recall’ performance measure was used for imbalanced dataset to analyse the performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9mLQS1aPnQoAaF9c_mv0A.png" /><figcaption>Figure 1: Walking and jogging class data are more commonly preset in datasets, indicating an imbalance in the distribution of data across training and test datasets. The data ratio between standing, seated and other classes is noticeably low, which may result in inaccurate model predictions.</figcaption></figure><h4>Feature Extractions with PCA</h4><p>PC2 captures 16.88% of the variance, while PC1 captures 36.79%. This indicates that more than 53% of the variance in the data is captured by the first two main components combined. This implies that the two major components shown in figure 2 may adequately describe the data.</p><p>Most likely, the data points are spread out all around the origin, extending along PCs 1 and 2. Since jogging and walking are distinct along PC1, it is possible that PC1 caught a component of exercise intensity, with jogging exhibiting and walking a higher intensity. Since PC2 separates activities, such as standing and sitting on the upper and lower stairs, it suggests that PC2 could record components of vertical movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*LHr4lbPmDQ0eOp_6rGpTRg.png" /><figcaption>Figure 2: The first two PCs capture 53% variance of data and well-represented by these two principal components. PC1 captured aspect of activity intensity, with jogging and walking. PC2 captured vertical movement standing, upstairs downstairs and sitting.</figcaption></figure><h4>Box Plots Analysis of Acceleration and Variance Metrics by Activity</h4><p>Only four boxes are displayed in this box plot, which was made for every variable that is attached to the report’s end. These data points are drawn outside of the whiskers, indicating that there are many outliers in the variables related to the y and z axes. A large range of values is displayed by the median value of all activities across all variables. Analysing the values from the data set shows varying values of “y-axis__root_mean_square,” “y-axis_maximum,” “y_axis_mean,” and “y-axis absolute maximum,” where some values are noticeably higher than others. Accelerometer data outliers can be challenging, particularly since extreme values may represent genuine movements or anomalies in the data collection process. Unusual activity, abrupt motions, or even sensor disruptions could be represented by outliers. The PCA algorithm was used to calculate the outliers and discussed in following part of report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Uig_RaQk_i6DAE5RzMGBA.png" /><figcaption>Figure 3:Box plots of variance and acceleration magnitude illustrate various datapoints outside the quantile Q1 and Q3 range which implies as a potential outlier in dataset. The large of datapoints outside whiskers may represent genuine movements with extreme values.</figcaption></figure><h4>Outlier dictation with PCA</h4><p>The Mahalanobis distance for PCs 1 and 2 is the robust method for calculating the outliers. To analyse the computed outliers, the threshold values of 4, 3.5, and 3 were used. There are only three outliers at the threshold value of 4, compared to a few at value 3.5 and several significant outliers at value 3. The identified outliers on the left side of the plots indicate the sitting class and grouped towards the PC2 between values 8 and 7, according to a comparison of Figure 4 with datapoints classified by PC1 and PC1 which demonstrate that the data points that have been detected are not true outliers. Comparably, in the PC1 vs. PC2 plot, the points found on the right side of the plot are classified as walking since they are closely associated with the walking class. It may therefore be the case that they are not true outliers, but rather a means of identifying either these or other real or distinct types of movement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tM4Zdb_GQWS3BJBOwqpS_g.png" /><figcaption>Figure 4: Identifying the outliers using the mahalanobis distance for PC1 and PC2 for threshold 3,3.5 and 4. A stricter threshold (4) identifies very few outliers, while a more lenient threshold (3) identifies many outliers.</figcaption></figure><p><strong>Features Extraction from Timeseries Dataset</strong></p><p>The variables below were extracted from a timeseries dataset and their contribution to the classification of human activity was taken into consideration while making the extraction choice. These features have been applied to a number of researches [1,2] that measure how well models perform in classifying human activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*A4iXC3ie7NpoIx8BRW4Chw.png" /></figure><h4>Activity, the Predictive Variable’s Behaviour</h4><p>Predictive variable activity was plotted against the user to determine the most popular activity performed by users in order to further analyse the data. It has been noted that the most frequent activity among users is waking, with jogging coming in second, and sitting being the least common activity among all users. One further illustration of the unbalanced data is provided by this plot. Data was collected from the users’ individual digital devices and data collected show that when users perform physical activities like walking or jogging, data collection happened. This suggests that the gadgets could be fitness trackers or made to capture the exercise data. It may also possible that while users were sitting, they were less likely to wear the devices or keep them active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*tXQzJBEJhMGQmVxuVlBAkg.png" /><figcaption>Figure 5: Activity class ‘walking ‘was the most popular activity, followed by jogging. The least frequent user actions include standing and sitting, which suggests that the data was collected when users were engaged in intense activities.</figcaption></figure><p>Change of Magnitude on Activities</p><p>Interesting observations about the relationship between acceleration magnitude and human activity density are made from this plot, which also offers important information about how users move. The narrow and high peak for standing at 9–10 magnitude and 2.5 density points to quick, powerful accelerations. This might be the result of a sudden change in weight distribution while standing still or the first movement made after getting up from a sitting position. One possible explanation for the two sitting peaks at density 1 and spread between 8 and 11 magnitudes could be a slight tilt in the body or fidget while seated.</p><p>Jogging’s long tail on the x-axis (1–15 magnitude) with low density (0.5) shows a large range of acceleration values occurring infrequently. The reasons for this could be uneven ground, changes in the intensity of jogging, or leg swing. Walking’s magnitude distribution (8–11) and density (up to 11) are higher than jogging’s, indicating a more targeted range of acceleration and a larger frequency of identical movements throughout each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*DkVlq01NVNVh9Dn7nz95eQ.png" /><figcaption>Figure 6: Peaks in sitting and standing behaviours show different patterns of acceleration, and jogging shows fluctuations over a broad range. Walking reveals a targeted acceleration range at a higher frequency, providing insight into the movement patterns of users during the various activities.</figcaption></figure><p>Figure 7 shows more detail at the peaks and changes in the density of dynamic activities like walking and jogging upstairs and downstairs and static activities like sitting and standing. The downstairs has a higher peak than the upstairs. Due to the user’s repeated vertical and horizontal accelerations from bouncing, the jogging has a lengthy tail of high magnitude on all axes with consistent density of data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*oUKu0QQG6L0WVRWrJpy7Fw.png" /><figcaption>Figure 7: Static activity like standing and sitting have brief peaks which represent sudden change in position while balancing the position or weight. Walking illustrated by smooth peak which implies that walking activity is repetitive movements. Downstairs have higher peaks than upstairs with high density.</figcaption></figure><h3>Data Clustering Using T-SNE Model</h3><p>In order to analyse the class grouping, PCA was used first. This revealed clearly defined clusters with some overlap. Using different perplexity levels, the T-SNE model was used to validate these clusters. Some grouping was seen at a perplexity of 2, but there was also a lot of scattered data, which was especially apparent in activities like walking. Jogging showed more distinct clusters, suggesting that the t-SNE captured some underlying similarities in the data, especially for jogging. separating between activities such as walking and standing was difficult, even with mild confusion. Data points decreased when the complexity was increased to 5, however meaningful clustering patterns were still difficult to find. This pattern continued at perplexities of 10 and 15, indicating that actions such as standing, walking, and going upstairs and downstairs have characteristics in common that make it more difficult t distinguish between them in low-dimensional T-SNE. The scattered distribution of data points and the absence of clear clustering leads to refined the perplexity parameter and check cluster with perplexity value, 1, 8, 12 however jogging and walking cluster become more clear with perplexity 1 with many other overlapping regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8SLi2VqgdUHsZ0iVr1B_g.png" /><figcaption>Figure 8: t-SNE captured some underlying similarities in the data, especially for jogging and walking, other datapoints are scattered around make it difficult to cluster the data into different classes.</figcaption></figure><h4>Clustering Using UMAP Model</h4><p>After T-SNE failed to validate the clustering observed in PCA, the UMAP model was used to validate the patterns of clustering in the dataset. The UMAP method identified clusters in the data by using parameters like n_neighbors, min_dist, and metric=’euclidean’. Surprisingly, the UMAP clustering supported the PCA results, especially when it came to differentiating between sitting and standing behaviours. Additionally, UMAP distinguished between walking and jogging groups, suggesting that these two activities have similar movement patterns. Walking, upstairs, and downstairs are likely to show overlapping features, like leg movement, which could make it more difficult to distinguish between them in the low-dimensional UMAP embedding. This shows that more customised features could be created in the future to enhance clustering efficiency and more accurately capture each aspect of these activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*zTEy6SG9gpnzekIrNtm76Q.png" /><figcaption>Figure 8: UMAP confirms the reported PCA clustering pattern with n_neighbors=40, min_dist=0.5, and metric=’euclidean’. UMAP grouped walking, jogging, standing, and sitting together; however, the walking class overlapped with the activities of the downstairs and upstairs. Walking and jogging are the most frequent performed activities.</figcaption></figure><p><strong>Signals for Activities</strong></p><p>The x-axis accelerometer output shows some low peaks interspersed with high peaks when walking. Each walking steps forward acceleration during the heel strike and backward acceleration are represented by these peaks. Walking’s y-axis signal is primarily downward and moves towards zero, with irregular large peaks. Higher peaks typically correspond to faster motion or more energetic steps. Walking steps per minute are correlated with peak frequency. While the z-axis displays the same peak pattern with time and the x-axis has more powerful peaks, jogging exhibits higher peaks along all axes. As the force of movement changes with each step above, stairs and downstairs have higher peaks; similarly, downstairs have several uneven peaks. It is clear that when one is seated, there is no movement and no energy expended, which means the axis will stay stable. Less peaks signify a shift in posture and help to balance the weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yFcW0Ngz5hCCk4fyf-QdQ.png" /><figcaption>Figure 9: Walking shows repeating peaks with different heights based on pace on all three axes (X, Y, and Z). In comparison to walking, jogging exhibits greater and more frequent peaks on all axes, indicating faster and stronger hits. Values on X, Y, and Z remain rather steady while sitting with the potential for small peaks related to moving. With every step, upstairs and downstairs display high peaks on Z with downstairs having bigger impact peaks. Standing causes brief high intensity peaks on X, Y from posture changes with Z</figcaption></figure><p>This blog post provides a comprehensive understanding of a specific dataset and the patterns that exist within the data. By exploring the techniques and insights shared here, you can apply similar exploratory data analysis (EDA) methods to your own datasets. The knowledge gained from this post will help you identify trends, uncover hidden patterns, and make informed decisions when analyzing your data. Whether you’re new to EDA or looking to refine your skills, the concepts discussed will equip you with the tools needed to effectively analyze and interpret your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef1e9beaf16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis of Diabetes Health Indicators]]></title>
            <link>https://medium.com/@zainab.mehmood/exploratory-data-analysis-of-diabetes-health-indicators-39a0d5c4aa1a?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a0d5c4aa1a</guid>
            <category><![CDATA[diabetes]]></category>
            <category><![CDATA[health-data-science]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 10:54:57 GMT</pubDate>
            <atom:updated>2024-09-04T11:02:25.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Dataset used in this EDA is from UC Irvine Machine Learning Repository which can be accessed from this link: <a href="https://archive.ics.uci.edu/dataset/242/energy+efficiency">https://archive.ics.uci.edu/dataset/242/energy+efficiency</a></p><h4>Description of Data</h4><p>The Behavioural Risk Factor Surveillance System (BRFSS) is an annual telephone survey that the CDC uses to gather data on health-related topics. Over 400,000 Americans participate in the annual survey, which gathers information on health-related risk behaviours, chronic illnesses, and the use of preventive measures. Since 1984, it has been held annually. This dataset, which includes 253,680 survey responses from the CDC’s BRFSS2015, is clean and belongs to the year 2015. There are two classes in the target variable ‘Diabetes_binary’. Indicators of prediabetes or diabetes range from 0 to 1. This dataset is not balanced (proportion of diabetes and no diabetes) with 21 exploratory variables. Data has no missing values, and some variables are continuous while others are categorical.</p><h3>Verifying the Aspects of Data</h3><p>To find the shape of the data some basic data exploration was performed. The outcome reveals that the dataset has 24206 duplicate rows. A total of 229474 rows were selected for analysis after duplicate rows were eliminated. The boxplots shows that the BMI has some of outliers, but outliers are not removed as they were significantly affecting the data and not part of this study. Simple histograms are used for viewing and comprehension which shows some variables are discrete and some are continuous. Box plots are used to evaluate outliers in data.</p><h3>Visualization of Multivariate</h3><p>The section explains the reasons of the plotting of these variables in this part, along with annotations of the plot’s trends. One useful method for quickly identifying which factors are statistically significantly associated with the response variable is to use a correlation matrix. The heatmap in Figure 1 illustrates all factors’ relationships with diabetes binary and identifies the most significant variables for diabetes based on the correlation matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tJK2HxfAugrjd2_T1U7uQ.png" /><figcaption>Figure 1: Correlation Heatmap to Show How Diabetes is correlated significantly with Other Exploratory Variables</figcaption></figure><p>Figure 2’s grid plot shows how the rate of diabetes in the United States relates to body mass index (BMI) and several health characteristics, such as the proportion of smokers who test positive or negative for the disease, as well as those who have heart attacks, strokes, or heart disease who also have a diabetes test. Similarly, the percentage of people having diabetes is indicated by alcohol consumption and high blood pressure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7LjpjE5SXjFn-ESnV8nlg.png" /><figcaption>Figure 2: Diabetic People and their Body Mass Index Relationship with Disease and Habits</figcaption></figure><p>The bar plot in Figure 3 shows how the distribution of diabetics in various age groups and can be used to explore the relationship between age and the disease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USapIYwUf3O0xIEywPlooQ.png" /><figcaption>Figure 3: Diabetic Distribution among Different Age Group of People in America</figcaption></figure><p>Plotting stacked bar charts on a grid is an easy way of analysing the distribution of categorical variables in respect to the response variable “diabetes_binary.” There are two levels of positivity and negativity for each plotted category variable which provide additional picture of how data distribution is unbalanced between diabetic and non-diabetic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Axbs10jaxWXTIy-K8DkKWQ.png" /><figcaption>Figure 4: Effect of Blood Pressure, Smoke, Cholesterol, Eating, Health and Walk on Diabetes</figcaption></figure><p>Figure 5 shows the association between the response variable and sex as well as other health factors. Gender and other health factors have an impact on the percentage of people who have diabetes and those who do not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDER_d431GtanyCLzkKlvw.png" /><figcaption>Figure 5: Gender Distribution for Diabetes and different Health Factors</figcaption></figure><h3>Plot’s Trends and Discussion</h3><p>Figure 1’s correlation heatmap demonstrates that diabetes and high blood pressure are most strongly connected (0.8 value). Diabetes and high cholesterol and alcohol intake are also favourably connected. Diabetes is least negatively related with sex, age, education, and income. It is positively correlated with smoking, BMI, and heart disease. Additional examination of these positive and negative correlations from plots indicates that a complicated interaction between several factors influences the risk of diabetes. While a higher BMI is a major contributing factor in figure 2, the other variables like drinking and smoking, as well as medical issues like high blood pressure and heart disease have effect on diabetes. BMI and diabetes have a positive association in all groups that are characterised by the other variables. Regardless of BMI, the percentage of people with diabetes is higher in smokers than in non-smokers.</p><p>In figure 3, younger age groups, the age-related increase in the rate of diabetes is more apparent. Between the ages of 18 and 24 and 25 and 29, the bars for those without diabetes expand substantially faster than those between the ages of 60 and 64 and 65 and 69. Overall, as people age, diabetes becomes more common. As you move from left to right, the bars representing those with diabetes increase larger while the bars representing those without diabetes get shorter. Despite of gender, the presence of any factors — smoking, alcohol use, heart disease or attacks, or high blood pressure — generally raises the percentage of individuals with diabetes in figure 5. Men tend to have larger percentages of diabetes patients than women do, particularly when it comes to smokers and people with high blood pressure.</p><p>As the visual analysis concludes, diabetes is most influenced by high blood pressure, heart disease, cholesterol, and its check, while diabetes is least affected by gender and income. Similarly, a person’s BMI can indicate whether or not they have diabetes, however it can be challenging to draw that conclusion from a high BMI.</p><p>The plots were generated using the R programming language, and both the code and the dataset used for this analysis are available on GitHub. You can access them at the following link: <a href="https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/Diabetes%20Health%20Indicators">GitHub Repository — Diabetes Health Indicators</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a0d5c4aa1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis : Concrete Compressive Strength]]></title>
            <link>https://medium.com/@zainab.mehmood/exploratory-data-analysis-concrete-compressive-strength-63f368c75b38?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f368c75b38</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 17:32:30 GMT</pubDate>
            <atom:updated>2024-02-04T17:32:30.976Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploratory Data Analysis : Concrete Compressive Strength</h3><p>Data set used from UCI repository</p><h3>1 Description of Data</h3><p>The most important component in civil engineering is concrete. The relationship between age and components and the compressive strength of concrete is very nonlinear. From laboratory data, the true compressive strength (MPa) of concrete for a given combination under a certain age (days) was determined. The data is unscaled and in raw form. There are 1030 instances (observations) and the 10 attributes from which eight quantitative input variables and one quantitative output variable. The response variable in this data set is concrete strength; the other eight variables — cement, fly ash, blast furnace slag, water superplasticizer, coarse aggregate, fine aggregate, and age are explanatory variables excluding the Id number. Except for age, which is expressed in days, all explanatory variables are used in m3 mixture are quantified in units of 1 kg. According to the construction theory, the first 28 days during production are when concrete can reach its maximum strength. This report illustrates multiple variables in various relationships to determine which variable significantly contributes to the attainment of concrete strength.</p><h3>2 Verifying the Aspects of Data</h3><h3>2.1 Distribution and Relationship between the Variables</h3><p>Plotting all the data produces a bell curve, which indicates that the distribution is nearly normal, so no adjustments are necessary. When using grid scatter plots, no two features appear to have a strong relation. Despite the fact that there appears to be some association between cement and compressive strength. Furthermore, data has no significant outliers that may affect the response variable.</p><h3>2.2 Statistical Measure</h3><p>Finding the Pearson Correlation coefficients gives a numerical representation of the correlations’ strength, which is used to further analyse the relationship between the variables. The correlation analysis indicates that the strongest positive relationship is found between cement and compressive strength. The other variables are water, superplasticizer with strong positive correlation.</p><p>In order to determine the key variables, the linear regression model is also used. The results indicate that the variables that are significant include water, fly ash, cement, and blast furnace slag. are significant since their p-values fall below the 0.5 threshold of significance. Plotting is used with these variables to show how they relate visually</p><h3>3. Visualization of Multivariate</h3><p>The section explains the reasons of the plotting of these variables in this part, along with annotations of the plot’s trends. and section 4 provides more discussion on trends. The figure 1 illustrate that cement content and age impact on concrete strength as these variables have significant impact on concrete strength according to linear regression model results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLAQh7irYmCO14TLOs_CSg.png" /><figcaption>Figure 1: Impact of Age and Cement Content on Concrete Comprehensive Strength (Mpa)</figcaption></figure><p>In addition, cement and water have a positive correlation and are significant for the response variable concrete strength. Figure 2 illustrates the significance of water in the production of concrete for mixing, hydration, and reaching strength in early ages of concrete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9kAaIkiLm46GZLt8qdiLw.png" /><figcaption>Figure 2: Water and Cement Content Compsition Impact of Concrete Strength</figcaption></figure><p>The fly ash is used as replacement content of cement sometimes for concrete production process. The figure 3 illustrate the use of these content and how these are used to achieve the concrete strength.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE-QxcwhQAtKG6RfKdyo7w.png" /><figcaption>Figure 3: Cement and Fly Ash Content Composition and Their effect on Concrete Strength</figcaption></figure><p>The mean values of the cement, water, fly ash coarse aggregate, and fine aggregate which are relevant variables based on correlation and linear regression modelling mare shown in Figure 4 and are utilised to attain a particular concrete strength. The figures provide insight into how these components combine to give concrete its strength.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vB8s8WnIk0OJb2OJoDHl6A.png" /><figcaption>Figure 4: Comparison of Five content of Concrete Composition to Achieve the Concrete Strength (MPa)</figcaption></figure><p>The chemical superplasticizer is used to substitute water in the concrete-making process; if more superplasticizer is used, less water is needed, and vice versa. The chemical link between water and concrete strength is depicted in the graphs in Figure 5. The linear regression model’s trend line illustrates how concrete strength increases as chemical content increases and how water content decreases as chemical content increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJLeO9gh9ULTbo8xH3poiQ.png" /></figure><h3>4. Plot’s Trends and Discussion</h3><p>From these plots following trends are observed on the relationships between these variables and compressive strength:</p><ul><li>Compressive concrete strength correlates positively with Cement, as cement increase in composition the strength increases even at earlier age.</li><li>High compressive concrete strength with a low Age requires more Cement.</li><li>Compressive concrete strength correlates positively with Age till 28 days and have significant impact on till 52 days,</li><li>Cement tends to require more Water as it increase to mixing and keeping the concrete hydrated,</li><li>Cement and fly ash are negatively correlates, fly ash and as fly ash composition increase the cement content reduce in composition.</li><li>Highest Compressive Strength achieve with higher content of cement and lower content of fly ash.</li><li>Superplasticizer negatively relate with water, increasing superplasticizer content reduces the water content.</li><li>Compressive concrete strength increases with superplasticizer content and for most case superplasticizer higher content is between 4 to 10 kg in m³</li></ul><p>Based on the plot analysis, it appears that the cement content in the composition has a stronger influence on compressive concrete strength than the contents. The concrete strength shows an increasing trend as its composition have increasing cement, which is especially apparent at earlier age. It’s interesting to note that more cement is needed to achieve good compressive strength at a young age. Furthermore, there is an important impact seen for up to 52 days in the positive correlation between compressive strength and age. Though 28 days have been considered to be the maximum number of days in building theory and industry to get increased concrete strength.</p><p>Higher cement and lower fly ash contents result in the highest compressive strength, emphasising the significance of these ingredients in the mixture. The significance of water in the mix is emphasised, showing that more water is needed to maintain adequate mixing and hydration of the concrete as cement content rises. Even so, superplasticizer content can, up to a point, replace water content. Similar to this, fly ash can partially replace cement in particular uses. In order to improve the strength of the concrete, a specific quantity of both fine and coarse aggregate is required. Every element in the composition is required to be present in at least the bare minimum amount. To reach the strength of the concrete, however, a particular amount of coarse and fine aggregate must be combined with more cement and water. In certain circumstances, superplasticizer and fly ash can be used in place of cement and water.</p><h3>GitHub Link for R code;</h3><p>https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/UCI-Concrete%20Data</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f368c75b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis Report: Glass Identification]]></title>
            <link>https://medium.com/@zainab.mehmood/data-analysis-report-glass-identification-ebb71b652bfc?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebb71b652bfc</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r-for-data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 08:02:17 GMT</pubDate>
            <atom:updated>2024-02-04T08:02:17.355Z</atom:updated>
            <content:encoded><![CDATA[<p>Data set from UCI Repository</p><h3>1. Description of Dataset</h3><p>The dataset describes that glass are categorised into one of six classes based on their chemical properties. The glass dataset’s attributes are calculated by nine input variables, as shown in table 1(a). The weight percentage in corresponding oxide is used to measure the chemical compositions of glass. Table 1 (b) lists seven different kinds of glass and float glass refers to the process of creating the glass.</p><p>The dataset contains 214 observations, and table 1(c) lists the unequal number of observations in each class. For class 4 (non-float processed car windows), there are no examples included in the dataset. Classes 1–4 and 5–7 of the datasets are categorised as window glass and non-window glass, respectively. There are 51 examples of glass that is not a window and 163 examples of window glass. If the observations were limited to window glass only, another separation of the data would be between float processed glass and non-float processed glass. There is greater balance in this division.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*8uzk88tLHexVSVhy2AmDWg.png" /></figure><h3>2. Verifying the Aspects of Data</h3><p>To verify the different aspects dataset, histogram, boxplot pair scatter plot and density plot are used. To statistically analysis the relation of RI and glass type with predictor variables linear regression model is used.</p><h3>2.1 Identification of Outliers</h3><p>To find the outliers, Boxplots are plotted, and the plots showed that there are outliers in all the variables expect magnesium. The K and Ba variables contain the most extreme outliers. Additionally displaying skewing in several variables, the Boxplots perform poorly when it comes to extreme outlier variables. However, no outliers were removed as it is not part of the report.</p><h3>2.2 Distribution and Relationship between Variables</h3><p>It appears that the distributions of RI, Na, Al, and Si are relatively normal (symmetric) based on the histograms of the variables. The distributions of the remaining variables seem to be asymmetric. Strong correlations do not seem to be present for the majority of the variable pairings in the scatterplot matrix. The RI, Ca pair, which has an obviously positive association, and possibly the RI, Si pair, which exhibits a somewhat negative relationship, are the outliers.</p><h3>2.3 Linear regression Model</h3><p>To identify the which predicator variables are more associated with refractive index and glass type simple linear regression models are used. Based on the linear mode results ‘Na’, ‘Mg’, ‘K’, ‘Ca’, and ‘Ba’ have p-values less than 0.05, indicating they are statistically significant predictors of refractive index RI. In case of glass type ‘Al’ seems to be statistically significant (p-value = 0.0354), indicating that ‘Al’ might be an important predictor for ‘glass-type’. Other variables, such as ‘Na’, also show some significance (p-value = 0.0842), but not as strongly as ‘Al’. In these results provide start point for finding trends abut simple linear model is not provide reasonable evidence which variable (chemical) will be strong indicator for reflective index and glass type.</p><h3>3. Visualization of Multi-Variate and Trends</h3><p>This part explains the reasons for the plotting of the variables and the annotation of the plot’s trends. Part 4 offers more details on the trends.</p><h3>3.1 Oxides that Predict the Glass Type</h3><p>Based on the findings of regression analysis, box plots were used to determine which two oxides could most accurately predict the kind of glass. The box plot results indicate that the two best oxides that are crucial in predicting the type of glass are sodium (Na) and aluminium (Al). The box plot of sodium and aluminium with different glass types is shown in figure 1 below. The different amounts of these two oxides will help in identifying the kind of glass for each of the seven categories of glass that are classified as window or non-window glass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwvfZafsPIBgYl4Z_GBcGg.png" /><figcaption>Figure 1 : Sodium (Na) and Aluminium (Al) Oxides as Predicator for Glass Type( Windows and Non-Windows)</figcaption></figure><p>Relying less on the regression model, the average quantity of oxides is plotted against the type of glass to visualise the presence of other oxides in various glass types. This provides a clear image, as illustrated in figure 2, of which oxide types would be taken into consideration to predict the glass type. Section 4 paragraph one discussed the trends and optimum oxides to consider while predicting the types of glass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKMT5q7a_R1fxtGlHNz3ww.png" /><figcaption>Figure 2: Oxides (chemicals) Average Amount Present in Glass Type(Windows and non-Windows)</figcaption></figure><h3>3.2 Oxides that Predict the Reflective Index (RI) of Glass</h3><p>The Refractive Index (RI) of glass with different oxides is shown on a correlation heat map in order to determine which variable has the greatest positive and least negative relationship with the response variable. The glass type and iron (Fe) have the strongest refractive index association.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*lURBTUGKNKi4VjZIFdA65w.png" /><figcaption>Figure 3: Correlation Matrix Heatmap to explain the correlation (Positive &amp; Negative) of Refractive Index with other Oxides.</figcaption></figure><p>A grid scatter plot was created to better explore the impact of oxide presence on the refractive index of glass. The results indicate that the existence of additional oxides may have an impact on the refractive index of glass in addition to glass type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stKrhU085uCTvQtzSvSx6Q.png" /><figcaption>Figure 4: Scatter Plots of Oxides to Show the Spread for Refracive Index and presence of Outliers</figcaption></figure><p>Plotting the regression model result allows for a deeper exploration of the data. According to the regression model, the refractive index may be significantly predicted by calcium (Ca), magnesium (Mg), and sodium (Na). Nevertheless, patterns and the most important oxides as a refractive index predictor are discussed in of paragraph two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVHmFUp_W2CnsLvelnu9HQ.png" /><figcaption>Figure 5: Most Significant Oxides to Predict the Refractive Index Based on Linear Regression Model Results</figcaption></figure><h3>4. Discussion</h3><p>The defining role of Na in the various glass types is indicated by the varied medians and diverse spreads in Na concentration. The differences in the median Na concentration lines inside the boxes indicate that different varieties of glass have different usual Na concentrations. This variety implies that Na has a major role in differentiating these types of glass. Furthermore, the wider spreads of boxes for kinds 6 and 7 suggest higher fluctuation in Na content, the narrower boxes for types 1–5 suggest more constant Na concentrations within these categories. This implies that the concentration of Na in some glass varieties may be closely monitored or controlled, which contributes to their unique characteristics. But it is fair to conclude — after seeing the oxide bar graphs for each type of glass — that the presence of iron, potassium, magnesium, and aluminium in glass contributes to its type of identification. Determining the optimal oxides for glass type prediction required through additional statistical analysis and data training.</p><p>Three distinct plots are analysed to identify important refractive index (RI) predictors. The type of glass is the most significant variable among the other variables that positively linked with RI, with a perfect correlation value of 1.0. This indicates that the type of glass has a significant impact on the RI, which is supported by the grid plots’ observed variations in RI for various glass types. Fe also shows favourable interaction with RI. Strong linear connections with RI are shown by the plots of Ba, Fe, and glass type, which are easily identifiable. However, the best fit line of linear mode says that Ca most significant indicator. Glass type and Ca followed by Ba can be considered as best predictor of refractive index.</p><h3>GitHub Link for Code</h3><p><a href="https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/glass%20identification%20-Exploratory%20Analysis">https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/glass%20identification%20-Exploratory%20Analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebb71b652bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[El-Nino Data Set: Exploratory-Data-Analysis]]></title>
            <link>https://medium.com/@zainab.mehmood/el-nino-data-set-exploratory-data-analysis-0c0f7993053e?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c0f7993053e</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dataanalyticscourse]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 04:48:39 GMT</pubDate>
            <atom:updated>2024-02-03T04:48:39.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>1.1 Description of Data</h3><p>The warm phase of the El Nino Southern Oscillation (ENSO) is known as El-Nino. Every three to seven years, there is a shift of the ocean and climate that lasts for nine to twelve months. El Nino, which is located in the Equatorial Pacific, affects weather patterns worldwide and is responsible for the unusually warm Pacific Ocean temperatures. There are twelve variables in the data. This report analyses the variations in “Air_Temp,” “Sea_Surface_Temp,” and the impact of the position of the buoys on temperature. For certain places, data from buoys taken from 1980. Rainfall, sun exposure, current levels, and subsurface temperatures are among the other data that were collected at various sites. The data contains missing values. Since certain buoys are not equipped to measure solar radiation, rainfall, or currents, these numbers vary depending on the specific buoy. Because some buoys were put into service earlier than others, the quantity of data that is accessible also varies depending on the buoy.</p><h3>1.2 Verifying the Different Aspects of Data</h3><h3>1.2.1 Distribution and Relationship between the Variables</h3><p>Initially, the data is looked for non-numeric values in the dataset and converted them in so that analysis would continue. There are 15133 missing values in the data due to buoys as defined in first section, but they are not imputed because they are not necessary for this report. Datetime format was used for the “Date” column, and all relevant columns were renamed. A data summary was calculated to determine how the variables were distributed and box plots and descriptive statistics are used to find outliers. There are no outliers observed in the box plots of latitude, longitude, zonal winds, meridional winds, humidity, air temperature, and sea surface temperature. The position of buoys was change to 180 degree and a new variable hemisphere is created based on latitude, longitude calculation.</p><h3>1.2.2 Statistical Measure</h3><p>To determine which factors are statistically significant for sea surface temperature, the linear regression model and correlation matrix are used in statistical testing. The p-value of the latitude, longitude, humidity, air temperature, zonal winds, and meridional winds is less than the significant value of 0.5, indicating their significance. According to the correlation matrix results, there is an positive correlation between latitude, longitude, zonal winds, and meridional winds. Latitude exhibits the maximum correlation value of 1, followed by longitude and zonal winds. Conversely, there is a negative correlation between sea surface temperature, air temperature, and humidity.</p><h3>1.3 Visualization of Multivariate</h3><p>The section explains the reasons of the plotting of these variables in this part, along with annotations of the plot’s trends. and section 4 provides more discussion on trends. The figure shows how frequently El Nino events occur in the dataset; a threshold of +0.5°C is used to identify anomalies related to El Nino. The El Nino event frequency in the northern and southern hemispheres is displayed using a map and bar chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhmlHKDwKjR0qaAyHP_2hQ.png" /><figcaption>Figure 1: Occurrence of El Nino Event with the Change in Buoys Position in Northern and Southern Hemispheres</figcaption></figure><p>The air and sea surface temperatures are highly dependent on the buoy’s position, which can vary dramatically. The impact of fluctuation on temperature is depicted in the image below, which has a plot grid. The last row grid provides more information about how the air and water temperatures vary at a given location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhgtxBcUm4SR1gNuTqajDg.png" /><figcaption>Figure 2: Impact of Buoys Position Change on Sea Surface and Air Temperature</figcaption></figure><p>The chart displays the time series of variations in air and sea surface temperatures during a period of eighteen years, from 1980 to 1998. The figures show trends and sudden shifts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*m7bPSnxkGn9-gHBYAMXccw.png" /><figcaption>Figure 3: Timeline for variation in Sea Surface Temperatures from 1980 to 1998 in North and south Hemispheres</figcaption></figure><p>The monthly interval of temperature variation for the years 1990 and 1997 is illustrated. It is evident that the temperature fluctuates somewhat steadily in the southern hemisphere and quite a bit in the northern hemisphere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*m7bPSnxkGn9-gHBYAMXccw.png" /><figcaption>Figure 4: Monthly Timeline of Sea Surface and Air Temperature for Year 1990 and 1997 in North and south Hemispheres</figcaption></figure><p>The air temperature has a linear relationship with sea temperature, and the position of the buoys affects the sea surface temperature. The winds and air humidity are affected by these temperature changes. and is useful in weather and rainfall forecasting. The figure below illustrates how variations in sea surface temperature affect humidity and the zonal and meridional winds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbdrqo4JpuTxswvtxRlk2g.png" /><figcaption>Figure 5: Variations in Humidity, Zonal Wind, and Meridional Wind in relation to Sea Surface Temperature Over the 18 Years</figcaption></figure><h3>1.1 Plot’s Trends and Discussion</h3><p>From these plots following trends are observed on the relationships between these variables and buoys position.</p><ul><li>Sea surface and air temperature has strong positive correlation relationship, as sea surface temperature arises the air temperature arises.</li><li>As humidity increases, air temperature tends to decrease, and vice versa.</li><li>The temperature changes with latitude as the position of buoys changes</li><li>The change in temperature and El-Nino events happened more in northern hemisphere then southern hemisphere.</li><li>The negative correlation indicates that high wind speed, associated with cool sea surface temperature.</li></ul><p>Plots of the relationships between the variables and buoy positions show different interesting patterns. First, there is a strong positive correlation between air and sea surface temperatures, meaning that air temperature tends to rise together with sea surface temperature. Furthermore, humidity and air temperature have an inverse relationship, which means that lower air temperatures are linked to higher humidity levels and vice versa. Temperature differences are largely dependent on geographic latitude; as buoys move along different latitudes, variances are evident. Compared to the southern hemisphere, the northern hemisphere sees more extreme variations in temperature as well as El Nino events. The sea surface temperature and wind speed are found to be negatively correlated, indicating that lower sea surface temperatures are related to higher wind speeds.</p><p>In both hemispheres, the air and sea surface temperatures have risen over time. In both hemispheres, the sea surface temperature peaked in 1997. Peak sea surface temperatures in the Northern and Southern Hemispheres, respectively, were around 28.5°C and 28.7°C. In 1998, the air temperature reached its highest point. Peak air temperature was 27.5°C in the North Hemisphere and 27.7°C in the South Hemisphere. The air temperature and the sea surface temperature are highly correlated. This is due to the fact that the ocean is a significant heat reservoir that affects the air’s temperature above it.</p><p><strong>GitHub Link for R code </strong><a href="https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/Einino%20Data%20Set">https://github.com/ZainabMCheema/Exploratory-Data-Analysis/tree/main/Einino%20Data%20Set</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c0f7993053e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walmart Sales Analysis SQL Project]]></title>
            <link>https://medium.com/@zainab.mehmood/walmart-sales-analysis-sql-project-6266c2192df7?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/6266c2192df7</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[walmart]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 16:07:54 GMT</pubDate>
            <atom:updated>2023-09-08T16:25:19.264Z</atom:updated>
            <content:encoded><![CDATA[<h4>About Project</h4><p>The goal of this project is to examine Walmart Sales data in order to comprehend top-performing branches and items, sales trends for various products, and consumer behavior. The goal is to investigate how sales methods might be made better and more effective. The [Kaggle Walmart Sales Forecasting Competition](<a href="https://www.kaggle.com/c/walmart-recruiting-store-sales-forecasting">https://www.kaggle.com/c/walmart-recruiting-store-sales-forecasting</a>) is where the dataset was collected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RlI4hzKAC3bVDV6YTU-FrQ.jpeg" /></figure><p>“In this hiring contest, job hopefuls are given historical sales information for 45 Walmart locations spread across several geographies. Participants must forecast the sales for each department in each store, which has multiple departments. Selected holiday markdown events are included in the dataset to increase the difficulty. Although it is recognized that these markdowns have an influence on sales, it can be difficult to forecast which departments will be impacted and how much.</p><h4>Purpose</h4><p>The major aim of thie project is to gain insight into the sales data of Walmart to understand the different factors that affect sales of the different branches.</p><h4><strong>About Data</strong></h4><p>This dataset contains sales transactions from a three different branches of Walmart, respectively located in Mandalay, Yangon and Naypyitaw. The data contains 17 columns and 1000 rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTpOep-XEsozMISpi4lvZA.png" /></figure><h4><strong>Data Wrangling</strong></h4><p>This is the first step where inspection of data is done to make sure <strong>**NULL**</strong> values and missing values are detected and data replacement methods are used to replace, missing or <strong>**NULL**</strong> values.</p><ol><li><strong><em>Build a database</em></strong></li></ol><pre>create database  if not exists  SalesDataWalmart;</pre><p><strong><em>2. Create table and insert the data.</em></strong></p><p>3. Select columns with null values in them. There are no null values in our database as in creating the tables, we set <strong>**NOT NULL**</strong> for each field, hence null values are filtered out.</p><pre><br>Create table if not exists WMsales (<br> invoice_id  varchar(30) Not null primary Key,<br> branch  varchar (5) not null,<br>    city varchar (30) not null,<br>    customer_type varchar (30) not null,<br>    gender  varchar(10) not null,<br>    product_line varchar (100) not null,<br>    unit_price  decimal(10,2) not null,<br>    quantity int not null,<br>    VAT  float(6,4) not null,<br>    total decimal (12,4) not null,<br>    date datetime not null,<br>    time TIME not null,<br>    payment_method varchar (15)  not null, <br>    cogs  decimal (10, 2) not null,<br>    gross_margin_pct float (11,9),<br>    gross_income decimal(12, 4) not null,<br>    rating float (2, 1)<br>);</pre><h4>Import Data from CSV</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pW4ZWTWZybsOXH_EKgB9gQ.png" /></figure><p>After creating a database, it’s time to import data from a CSV file. For this select import and a new window will open Select the path from the local machine.</p><p><em>A snippet of the table view</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46g3LezAmGVseHIXMhymaQ.png" /></figure><h4><strong>Feature Engineering</strong></h4><ol><li>Add a new column named `<strong>time_of_day`</strong> to give insight of sales in the Morning, Afternoon and Evening. This will help answer the question on which part of the day most sales are made.</li></ol><pre>select <br> time,<br>    (case <br>  when `time` between &quot;00:00:00&quot; and &quot;12:00:00&quot; then &quot;Morning&quot;<br>        when `time` between &quot;12:01:00&quot; and &quot;16:00:00&quot; then &quot;Afternoon&quot;<br>        else  &quot;Evening&quot; <br>    end <br>    ) As time_of_day<br>from wmsales; <br>alter table wmsales add column time_of_day  varchar(30);<br>update wmsales<br>set time_of_day= (<br> case <br>  when `time` between &quot;00:00:00&quot; and &quot;12:00:00&quot; then &quot;Morning&quot;<br>        when `time` between &quot;12:01:00&quot; and &quot;16:00:00&quot; then &quot;Afternoon&quot;<br>        else  &quot;Evening&quot; <br>    end<br>);</pre><p>2. Add a new column named <strong>`day_name` </strong>that contains the extracted days of the week on which the given transaction took place (Mon, Tue, Wed, Thur, Fri). This will help answer the question on which week of the day each branch is busiest.</p><pre>--- -day name<br>select<br> date,<br>    dayname(date)<br>from wmsales;<br>alter table wmsales add column day_name varchar(10);<br>update  wmsales<br>set day_name= dayname(date);</pre><p>3. Add a new column named `<strong>month_name</strong>` that contains the extracted months of the year on which the given transaction took place (Jan, Feb, Mar). Help determine which month of the year has the most sales and profit.</p><pre>-----------  Month_name<br>select <br> date,<br>    monthname(date)<br>from wmsales;<br>alter table wmsales add column month_name varchar(15);<br>update  wmsales<br>set month_name= monthname(date);</pre><p>An updated data set with day_name, month_name and time_of_day</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_151jdqNsZa_lZhCVmk9mA.png" /></figure><h4><strong>Exploratory Data Analysis (EDA)</strong></h4><p>Exploratory data analysis is done to answer the listed questions and aims of this project.</p><p><strong><em>Business Questions To Answer</em></strong></p><p><strong>Generic Question</strong></p><ol><li><strong><em>How many unique cities does the data have?</em></strong></li><li><strong><em>In which city is each branch?</em></strong></li></ol><pre>select<br> distinct city<br>from wmsales;<br>-- 2. In which city is each branch?<br>select<br> distinct city,<br>    branch<br>from wmsales;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*71bT9kHS4zCDaCL2pWY-pQ.png" /><figcaption>Distinct City</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*YW4kQoSh3TCNIGCbFxWP3g.png" /><figcaption>Distinct Branches in each city</figcaption></figure><h3><strong>Product Analysis</strong></h3><p><strong><em>1. How many unique product lines does the data have?</em></strong></p><pre>--------------- 1. How many unique product lines does the data have?-----------<br>select <br> count(distinct product_line)<br>from wmsales;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*QhMEUNTZkDiYN9pbaBCPmg.png" /><figcaption>No of Product lines</figcaption></figure><p><strong><em>2. What is the most common payment method?</em></strong></p><p><strong><em>3. What is the most selling product line?</em></strong></p><p><strong><em>4. What is the total revenue by month?</em></strong></p><pre>------------------------- 2. What is the most common payment method?-----------<br>select <br> payment_method,<br> count( payment_method) as cnt<br>from wmsales<br>group by payment_method<br>order by  cnt desc;<br>----------- 3. What is the most selling product line?---------------<br>select <br> product_line,<br> count( product_line) as cnt<br>from wmsales<br>group by product_line<br>order by  cnt desc;<br>--------------- 4. What is the total revenue by month? ------------<br>Select <br> month_name as Month,<br>    sum(total) as Total_Revenue <br>from wmsales<br>group by month_name<br>order by Total_Revenue Desc ;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*RGy-RNdOQKeOBjYtMxVQbg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*0CXyl3Cpg61MwP66f9dLrg.jpeg" /></figure><p><strong><em>5. What month had the largest COGS?</em></strong></p><p><strong><em>6. What product line had the largest revenue?</em></strong></p><p><strong><em>7. What is the city with the largest revenue?</em></strong></p><p><strong><em>8. What product line had the largest VAT?</em></strong></p><pre>----------------------- 5. What month had the largest COGS?----------<br>select <br> month_name as month,<br>    sum(cogs) as cogs<br>from wmsales<br>group by month_name<br>order by cogs desc;<br>---------------- 6. What product line had the largest revenue? ---------------<br>select <br> product_line,<br>    sum(total) as Total_revenue <br>from wmsales<br>group by product_line<br>order by Total_revenue  desc;<br>---------------------- 7. What is the city with the largest revenue?-----------------<br>select <br> city,<br>    sum(total) as Total_revenue <br>from wmsales<br>group by city<br>order by Total_revenue  desc;<br>-------------- -8. What product line had the largest VAT?<br>select <br> product_line,<br>    sum(VAT) as Valueable_Tax<br>from wmsales<br>group by product_line<br>order by Valueable_Tax  desc;</pre><p><strong><em>10. Which branch sold more products than average product sold?</em></strong></p><p><strong><em>11. What is the most common product line by gender?</em></strong></p><p><strong><em>12. What is the average rating of each product line?</em></strong></p><pre>---- 10. Which branch sold more products than average product sold?-----<br>select <br> branch ,<br>    sum(quantity) as qty<br>from wmsales<br>group by branch<br>having sum(quantity) &gt; <br> (select  avg(quantity) from wmsales);<br>------------ 11. What is the most common product line by gender?-------<br>select<br> gender,<br>    product_line,<br>    count(gender) as total_count<br>from wmsales<br>group by gender, product_line<br>order by total_count desc;<br><br>------- 12. What is the average rating of each product line?-----------<br>select<br> round(avg (rating) , 2) as avg_rating,<br>    product_line<br>from wmsales<br>group by product_line<br>order by avg_rating desc;</pre><h3>Sales Analysis</h3><p><strong><em>1. Number of sales made in each time of the day per weekday</em></strong></p><p><strong><em>2. Which of the customer types brings the most revenue?</em></strong></p><p><strong><em>3. Which city has the largest tax percent/ VAT (**Value Added Tax**)?</em></strong></p><p><strong><em>4. Which customer type pays the most in VAT?</em></strong></p><pre>-------- -----1. Number of sales made in each time of the day per weekday--------<br>select<br> time_of_day,<br>    count(*) as total_sales<br>from wmsales<br>where day_name = &quot;Sunday&quot;<br>group by time_of_day<br>order by total_sales desc;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*UfMs80BydNNAFk16GuEZ5Q.png" /><figcaption>Number of sales made each day</figcaption></figure><pre>----------- 2. Which of the customer types brings the most revenue?---<br>select<br> customer_type,<br>    round (sum(total), 2) as total_revenue<br>from wmsales<br>group by customer_type<br>order by total_revenue;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*YUDGFh7uy-_HehWdetA41w.png" /><figcaption>The customer brings the most revenue</figcaption></figure><pre>--------------------------- 3. Which city has the largest tax percent/ VAT (**Value Added Tax**)?--<br>select<br> city,<br>    avg(VAT) as value_added_tax<br>from wmsales<br>group by city<br>order by value_added_tax desc;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*6lLRbl9C06oyC5GncKQMSA.png" /><figcaption>City Contribution in VAT</figcaption></figure><pre>--------------------- 4. Which customer type pays the most in VAT?-----------<br>select<br> customer_type,<br>    avg(VAT) as value_added_tax<br>from wmsales<br>group by customer_type<br>order by value_added_tax desc;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*bxVSXEaE49Tue62-paysVA.png" /><figcaption>Customers contributing in VAT</figcaption></figure><h3>Customer Analysis</h3><ol><li><strong><em>How many unique customer types does the data have?</em></strong></li></ol><pre>------------- 1. How many unique customer types does the data have?----------<br>select<br> distinct (customer_type)<br>from wmsales;</pre><p><strong><em>2. How many unique payment methods does the data have?</em></strong></p><pre>----------- . How many unique payment methods does the data have?-----<br>select<br> distinct (payment_method)<br>from wmsales;</pre><p><strong><em>3. What is the most common customer type?</em></strong></p><pre>-------------------------- 3. What is the most common customer type?--<br>select<br> customer_type,<br>    count(*) as total_count<br>from wmsales<br>group by customer_type<br>order by total_count;</pre><p><strong><em>4. Which customer type buys the most?</em></strong></p><pre>------------ 4. Which customer type buys the most?----------<br>select<br> customer_type,<br>    count(*) as total_count<br>from wmsales<br>group by customer_type<br>order by total_count;<br></pre><p><strong><em>5. What is the gender of most of the customers?</em></strong></p><pre>-------------------------- 5. What is the gender of most of the customers?------<br>select<br> gender,<br>    count(*) as gender_count<br>from wmsales<br>group by gender<br>order by gender_count desc;</pre><p><strong>6. What is the gender distribution per branch?</strong></p><pre>------------------ 6. What is the gender distribution per branch?---------<br>select<br> gender,<br>    count(*) as gender_count<br>from wmsales<br>where branch = &quot;C&quot;<br>group by gender<br>order by gender_count desc;</pre><p><strong><em>7. Which time of the day do customers give most ratings?</em></strong></p><pre>-------------- 7. Which time of the day do customers give most ratings?-----<br>select<br> time_of_day,<br>    avg(rating) as avg_rating<br>from wmsales<br>group by time_of_day<br>order by avg_rating desc;</pre><p><strong>8. Which time of the day do customers give most ratings per branch?</strong></p><pre>------------ 8. Which time of the day do customers give most ratings per branch?----<br>select<br> time_of_day,<br>    branch,<br>    avg(rating) as avg_rating<br>from wmsales<br>group by time_of_day, branch<br>order by avg_rating ;<br><br><br>select<br> time_of_day,<br>    avg(rating) as avg_rating<br>from wmsales<br>where branch = &quot;C&quot;<br>group by time_of_day<br>order by avg_rating ;</pre><p>9. Which day fo the week has the best avg ratings?</p><pre>---------------------- 9. Which day fo the week has the best avg ratings?--------------<br>select<br> day_name,<br>    avg(rating) as avg_rating<br>from wmsales<br>group by day_name<br>order by avg_rating desc;</pre><p>10. Which day of the week has the best average ratings per branch?</p><pre>----- 10. Which day of the week has the best average ratings per branch?--<br>select<br> day_name,<br>    avg(rating) as avg_rating<br>from wmsales<br>where branch= &quot;A&quot;<br>group by day_name<br>order by avg_rating desc;</pre><h4><strong>Revenue And Profit Calculations</strong></h4><pre>------ $ total(gross_sales) <br>select<br> sum(VAT+cogs) as total_grass_sales<br>from  wmsales;<br>----- gross profit-----------<br>SELECT <br> (SUM(VAT + COGS) - COGS) <br>FROM wmsales;<br><br>SELECT (SUM(ROUND(VAT, 2) + COGS) - COGS) FROM wmsales;</pre><h3>Conclusion</h3><p>In this data analysis project, we embarked on a journey to gain valuable insights from Walmart’s sales data. We began by preparing and exploring the dataset, cleaning any missing or null values, and engineering new features to help us uncover meaningful patterns.</p><p>We addressed a variety of questions, ranging from understanding product performance and sales trends to diving into customer behavior. These insights are crucial for Walmart’s sales strategies and can guide future optimizations.</p><p>Throughout our analysis, we made use of SQL queries to extract relevant information from the dataset. We also computed important metrics such as COGS (Cost of Goods Sold), VAT (Value Added Tax), total revenue, and gross profit to better understand the financial aspects of Walmart’s operations.</p><p>Some key takeaways from our analysis include:</p><ul><li>Identification of top-performing product lines and branches.</li><li>Analysis of sales trends, which can inform sales strategies and modifications.</li><li>Profiling of customer segments and their profitability.</li></ul><p>The data-driven decisions made possible through this analysis can contribute to improved sales strategies, inventory management, and overall business performance.</p><p>While this project has provided valuable insights, it’s important to note that data analysis is an ongoing process. As Walmart continues to collect sales data, the potential for further analysis and refinement of strategies remains. This project serves as a foundation for future endeavors in enhancing Walmart’s sales forecasting and optimizing its operations.</p><p>Feel free to include any specific findings or results from your analysis in this section to provide a more detailed conclusion. Additionally, you can summarize the impact of your analysis on Walmart’s business strategies and operations.</p><p><strong>Github Link for source code file</strong></p><p><a href="https://github.com/ZainabMCheema/DataAnalystProject/tree/main/WalmartSalesAnalysis-Project">DataAnalystProject/WalmartSalesAnalysis-Project at main · ZainabMCheema/DataAnalystProject</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6266c2192df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing Market Insights: A Data Analysis Project in the Food & Beverage Industry]]></title>
            <link>https://medium.com/@zainab.mehmood/unleashing-market-insights-a-data-analysis-project-in-the-food-beverage-industry-bc989bda8284?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc989bda8284</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[food-and-drink]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 11:34:45 GMT</pubDate>
            <atom:updated>2023-09-06T13:19:50.499Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, businesses are constantly seeking ways to gain a competitive edge. One avenue that has gained significant traction is data analysis, which can provide invaluable insights to drive informed decision-making. In this blog post, we’ll explore a completed data analysis project that delves into the food and beverage industry. The project’s primary objective is to provide critical insights to the marketing team, helping them make data-backed decisions. Let’s dive into the details of this exciting project.</p><h3><strong>Project Overview</strong></h3><p><em>Dataset Size</em>: 100,000 Rows</p><h4>CodeX</h4><p>CodeX is a <strong>German beverage company</strong> which is recently <strong>launched</strong> in India. They launched their energy drink in <strong>10 cities in India</strong>.CodeX conducted a survey in those 10 cities and received results from 10k respondents.<br>The survey was based on consumer behaviour questions like their purchasing habits, their feedback about energy drinks available in the market, pricing, packaging etc. The survey question file is attached at the end of this article.</p><p>Their Marketing Team wants their Data Analyst to <strong>convert</strong> these survey <strong>results</strong> to meaningful <strong>insights</strong> which the team can use to drive actions.The Marketing Team have asked to share certain insights. They have also asked to share meaningful recommendations from the data or external factors etc.</p><p><strong>Project Importance</strong></p><p>Understanding the importance of this project is essential before delving into its details. In the highly competitive food and beverage industry, having a deep understanding of consumer preferences and market dynamics can be a game-changer. Here are some of the key reasons why this project is pivotal</p><ol><li>Data-Driven Decision Making: With access to a massive dataset of 100,000 rows, this project can provide data-backed insights to guide marketing strategies.</li><li>Competitive Advantage: Knowing what competitors are doing and why consumers prefer their brands can help in devising strategies to gain a competitive edge.</li><li>Targeted Marketing: Understanding demographics, consumer preferences, and purchase behavior enables the marketing team to tailor their campaigns more effectively.</li><li>Product Enhancement: Insights into product preferences and improvements can lead to better product development.</li></ol><h4>Star Schema</h4><p>Now, let’s delve into the specific Key Performance Indicators (KPIs) and project design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Qywk4on-cfabiu38igid0A.png" /><figcaption>Star Schema</figcaption></figure><h3>Project KPIs</h3><p>The success of any data analysis project lies in defining clear Key Performance Indicators. Here are the KPIs for this project:</p><ol><li>Demographic Insights: Understand the demographics of energy drink consumers, including gender, age, and which marketing strategies resonate most with them.</li><li>Consumer Preferences: Identify preferred ingredients and packaging choices among respondents.</li><li>Competition Analysis: Identify market leaders and discern why consumers prefer those brands over ours.</li><li>Marketing Channels and Brand Awareness: Determine which marketing channels are most effective in reaching the target audience and gauge brand awareness.</li><li>Brand Penetration: Measure overall brand perception and identify areas for improvement. Determine focus cities for brand expansion.</li><li>Purchase Behavior: Understand where and when consumers prefer to purchase energy drinks and what influences their decisions.</li><li>Product Development: Determine which aspects of product development (branding, taste, availability) should be prioritized.</li></ol><h4>Project Design</h4><p>The project design is crucial for gathering meaningful insights. It comprises two primary sections: Primary Insights and Secondary Insights.</p><p><strong><em>Primary Insights</em></strong></p><p>Primary insights are derived from the survey responses and focus on understanding consumer behavior within the dataset. The following questions guide this section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flZ2dCn9PP3Oj1FmJNfU4g.png" /></figure><p><strong><em>Demographic Insights:</em></strong> Who prefers energy drinks more in terms of gender and age groups? Which marketing strategies resonate with the youth?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqqJSgzedqoyo6rA4IRXHA.png" /><figcaption>Demographic of Respondents</figcaption></figure><p><strong><em>Demographic Insights</em></strong></p><p><strong>a. Who prefers energy drinks more? (male/female/non-binary?)</strong></p><p>Problem: Understanding the gender-based preferences of energy drink consumers is vital for tailored marketing efforts.</p><p>Solution: Out of 10,000 respondents, 60% are male, indicating a clear preference among males for energy drinks. The marketing team should craft campaigns that resonate with this demographic, highlighting the aspects of energy drinks that appeal to them.</p><p><strong>b. Which age group prefers energy drinks more?</strong></p><p><strong>Problem</strong>: Identifying the age group with the highest preference for energy drinks is crucial for targeting the right audience.</p><p><strong>Solution: </strong>The survey reveals that more than 50% of respondents belong to the 19–30 age group. To maximize reach, marketing campaigns should be focused on this young demographic, with content and messaging tailored to their preferences.</p><p><strong>c. Which type of marketing reaches the most Youth (15–30)?</strong></p><p><strong>Problem:</strong> Determining the most effective marketing channel for reaching the youth demographic (ages 15–30) is essential for optimizing marketing efforts.</p><p><strong>Solution: </strong>The data highlights that online ads are highly effective in reaching the 15–30 age group, with 3,373 respondents influenced by this channel. To engage this demographic further, the marketing team should prioritize online advertising campaigns.</p><p><strong><em>Consumer Preferences:</em></strong> What ingredients and packaging choices do respondents prefer for energy drinks?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awknC3oNygxJVxHlbEsCuA.png" /><figcaption>Consumer Preferences</figcaption></figure><p><strong>a. What are the preferred ingredients of energy drinks among respondents?</strong></p><p><strong>Problem: </strong>Knowing the preferred ingredients in energy drinks helps in product development and marketing.</p><p><strong>Solution: </strong>Caffeine and vitamins are the top expected ingredients. Marketing should emphasize these ingredients in product branding and promotion to align with consumer preferences.</p><p><strong>b. What packaging preferences do respondents have for energy drinks?</strong></p><p><strong>Problem:</strong> Packaging plays a crucial role in consumer choices. Understanding preferences can guide branding and packaging decisions.</p><p><strong>Solution:</strong> Compact and portable cans are in high demand, closely followed by innovative bottle designs. The marketing team should consider packaging that reflects these preferences and appeals to consumers.</p><p><strong><em>Competition Analysis: </em></strong>Who are the current market leaders, and what sets them apart?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP8KB8kVGc2ZOi44rpa65w.png" /><figcaption><strong><em>Competition Analysis</em></strong></figcaption></figure><p><strong>a. Who are the current market leaders?</strong></p><p><strong>Problem:</strong> Identifying market leaders is vital for understanding the competitive landscape.</p><p><strong>Solution:</strong> Cola Coka and Bepsi emerge as market leaders. The marketing team should analyze their strategies and identify opportunities to differentiate and compete effectively.</p><p><strong>b. What are the primary reasons consumers prefer those brands over ours?</strong></p><p><strong>Problem:</strong> Understanding why consumers prefer competitors’ brands provides insights for improving our offerings.</p><p><strong>Solution:</strong> The top reason for consumer brand preference is brand reputation. CodeX should focus on enhancing its brand image and reputation through strategic branding campaigns and initiatives.</p><p><strong><em>Marketing Channels and Brand Awareness:</em></strong> Which marketing channels are most effective, and how aware are consumers of our brand?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*269J_FLHi-jWB1NfEC4jxw.png" /></figure><p><strong>a. Which marketing channel can be used to reach more customers?</strong></p><p><strong>Problem:</strong> Identifying the most effective marketing channels is crucial for resource allocation.</p><p><strong>Solution: </strong>Online ads have proven to be the most effective channel, reaching a significant number of consumers. The marketing budget should be allocated accordingly to maximize online ad exposure.</p><p><strong>b. How effective are different marketing strategies and channels in reaching our customers?</strong></p><p><strong>Problem:</strong> Assessing the effectiveness of marketing strategies is essential for optimizing future campaigns.</p><p><strong>Solution:</strong> Based on the data, online ads have proven highly effective and cost-efficient. The marketing team should continue to invest in this channel while exploring opportunities for improvement in other channels</p><p><strong><em>Brand Penetration: </em></strong>What is the overall perception of our brand, and where should we focus for expansion?</p><p><strong>a. What do people think about our brand? (overall rating)</strong></p><p><strong>Problem</strong>: Understanding brand perception is crucial for brand improvement strategies.</p><p><strong>Solution:</strong> With a 3.3 rating, CodeX aligns with the industry average. To improve, the focus should be on increasing positive responses. Efforts should target enhancing the product’s taste and availability.</p><p><strong>b. Which cities do we need to focus more on?</strong></p><p><strong>Problem:</strong> Identifying cities for brand expansion is critical for growth.</p><p><strong>Solution: </strong>The data reveals that neutral and negative responses are prevalent in certain cities. Marketing efforts should concentrate on improving brand perception in these cities to foster growth and positive brand association.</p><p><strong>Purchase Behavior:</strong> Where do respondents prefer to buy energy drinks, and what influences their decisions?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huP7n1V6QwTw7MnAk4K4pQ.png" /></figure><p><strong>a. Where do respondents prefer to purchase energy drinks?</strong></p><p><strong>Problem:</strong> Knowing preferred purchase locations guides distribution strategies.</p><p><strong>Solution:</strong> Supermarkets are the most common choice for energy drink purchases. CodeX should strengthen its presence in these retail outlets and explore partnerships to enhance visibility.</p><p><strong>b. What are the typical consumption situations for energy drinks among respondents?</strong></p><p><strong>Problem:</strong> Understanding consumption situations helps tailor marketing strategies.</p><p><strong>Solution:</strong> Respondents mainly consume energy drinks during sports/exercise and while studying/working late. Marketing campaigns should align with these situations, highlighting energy boost benefits.</p><p><strong>c. What factors influence respondents’ purchase decisions, such as price range and limited edition packaging?</strong></p><p><strong>Problem:</strong> Knowing purchase influencers helps in pricing and packaging decisions.</p><p><strong>Solution:</strong> Price preferences fall within the range of 50–99 for 43% of consumers. CodeX should consider this range while setting prices. Additionally, consumers are open to limited edition packaging, indicating an opportunity for creative packaging designs.</p><p><strong>a. Which area of business should we focus more on in our product development? (Branding/taste/availability)</strong></p><p><strong>Problem:</strong> Identifying areas for product development is crucial for improving the product.</p><p><strong>Solution:</strong> Availability emerges as a key area for improvement, with only 20% of consumers choosing CodeX due to its availability. CodeX should prioritize expanding its distribution network.</p><p><strong>CodeX Brand Performance Analysis:</strong> What areas of product development need more attention?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heh12LOW9SNyuSQl3uoftQ.png" /></figure><p><strong><em>Recommendations for CodeX</em></strong>: Immediate product improvements, ideal pricing strategies, marketing campaigns, potential brand ambassadors, and target audience identification.</p><ol><li>Availability: Focus on expanding product availability to reach a wider consumer base.</li><li>Health Concern Survey: Conduct a survey related to health concerns to address consumer health preferences.</li><li>Limited Edition Packaging: Experiment with limited edition packaging to attract consumers.</li><li>Price Range: Set prices within the 50–150 range, varying by city as per consumer expectations.</li><li>Marketing Campaigns: Implement targeted marketing campaigns, including social media, influencer marketing, and online retail advertising.</li><li>Brand Ambassador: Consider influential personalities like Virat Kohli, Neeraj Chopra, or MS Dhoni as brand ambassadors to connect with the target audience.</li><li>Target Audience: Continue focusing on the youth demographic (15–30), which forms a substantial portion of consumers.</li></ol><h4>Conclusion</h4><p>In today’s competitive landscape, data analysis projects like this one are invaluable for businesses in the food and beverage industry. By harnessing the power of data, the marketing team can make informed decisions, enhance brand perception, and stay ahead of the competition. This project serves as a testament to the importance of data-driven strategies in shaping the future of the industry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc989bda8284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization with R ggplot Library]]></title>
            <link>https://medium.com/@zainab.mehmood/data-visualization-with-r-ggplot-library-863c0fe11de1?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/863c0fe11de1</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[r-language]]></category>
            <category><![CDATA[ggplot2]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 08:18:55 GMT</pubDate>
            <atom:updated>2023-09-01T08:18:55.345Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Vital Role of Data Visualization with R’s ggplot Library</strong></p><p>The use of data visualization, particularly with the R ggplot library, is of paramount importance in the realm of data analysis and communication. Data visualization transforms raw data into clear, insightful visuals that enable analysts and decision-makers to glean valuable insights from complex datasets. One key aspect of ggplot’s importance lies in its versatility and flexibility, allowing users to create a wide range of plots and graphics that suit their specific needs. Whether it’s creating elegant scatter plots, informative bar charts, or intricate heatmaps, ggplot provides a comprehensive toolkit to visually represent data effectively.</p><p><strong>Enhancing Understanding and Communication Through ggplot Visualizations</strong></p><p>Furthermore, the effectiveness of ggplot visualizations extends beyond just data exploration. They serve as powerful tools for communication. Well-designed plots can distill complex information into easily digestible formats, making it easier to convey findings and insights to diverse audiences, including non-technical stakeholders. ggplot’s customizable aesthetics and layering system enable users to add context and annotations to their plots, enhancing their ability to tell a compelling data-driven story. This clarity and storytelling capability make ggplot a vital component of data analysis, enhancing data-driven decision-making processes across various domains, from business analytics to scientific research. Ultimately, ggplot empowers data professionals to unlock the full potential of their data by making it not only understandable but also impactful.</p><p><strong>Installation of packages and Importing Libraries in R</strong></p><pre>install.packages(&quot;tidyverse&quot;)<br>library(tidyverse)<br>install.packages(&quot;gapminder&quot;)<br>library(gapminder)<br>View(gapminder)<br>data(&quot;gapminder&quot;)<br>install.packages(&quot;ggridges&quot;)<br>library(ggridges)<br>install.packages(&quot;patchwork&quot;)<br>library(patchwork)<br>install.packages(&quot;viridis&quot;)<br>install.packages(&quot;viridisLite&quot;)<br>library(viridis)<br>install.packages(&quot;hrbrthemes&quot;)<br>library(hrbrthemes)<br>install.packages(&quot;hrbrthemes&quot;)<br>library(hrbrthemes)<br>library(gapminder)</pre><p><strong>Working with Starwars Data Set</strong></p><p>In this exploration, we delve into the starwars dataset, aiming to showcase various data visualization techniques encompassing both numeric and categorical variables. Within this particular subset of the starwars dataset, we have incorporated distinct attributes for each entry. Notably, the ‘name’ variable serves as a unique identifier for each record; however, it will remain untouched throughout our analysis. We turn our focus to ‘height’ and ‘mass,’ representing numeric variables, and ‘gender’ and ‘hair_color,’ which fall under the category of categorical variables.</p><pre>data()<br>?starwars<br>starwars %&gt;%<br>  select(name, height, mass, gender, hair_color) %&gt;%<br>  head()</pre><pre>## # A tibble: 6 x 5<br>## name height mass gender hair_color<br>## &lt;chr&gt; &lt;int&gt; &lt;dbl&gt; &lt;chr&gt; &lt;chr&gt;<br>## 1 Luke Skywalker 172 77 masculine blond<br>## 2 C-3PO 167 75 masculine &lt;NA&gt;<br>## 3 R2-D2 96 32 masculine &lt;NA&gt;<br>## 4 Darth Vader 202 136 masculine none<br>## 5 Leia Organa 150 49 feminine brown<br>## 6 Owen Lars 178 120 masculine brown, grey</pre><p><strong>Plotting Chart with a Single Numeric Variable</strong></p><p>Let’s start with a single numeric variable (height). In this figure we’ve created a histogram, a density plot, a boxplot and a violin plot with the data. Here is the code and the outputs.</p><pre>p1 &lt;- starwars %&gt;%<br>ggplot(aes(x = height)) +<br>geom_histogram(binwidth = 20,<br>show.legend = F,<br>alpha = .5) +<br>labs(title = &quot;Histogram&quot;,<br>x = &quot;Height&quot;,<br>y = &quot;Count&quot;)<br><br>print(p1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*TceFo82UMy6WXd4MQIP1Ow.png" /></figure><pre>p2&lt;-starwars %&gt;% <br>  ggplot(aes(x= height))+<br>  geom_density(aes(fill=&quot;blue&quot;),<br>               show.legend = F,<br>               alpha=0.5)+<br>  labs(title = &quot;density chart&quot;,<br>       x=&quot;height&quot;,<br>       y=&quot;probability&quot;)<br>print(p2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*xoGn4GWoFQjZooA16zMSDA.png" /></figure><pre>p3&lt;- starwars %&gt;% <br>  ggplot(aes(x=height))+<br>  geom_boxplot(show.legend = F,<br>               alpha=0.5)+<br>  labs(title = &quot;boxplot chart&quot;,<br>       x=&quot;height&quot;)<br>print(p3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*DPlCvOD5C7B-9EHNznDn1Q.png" /></figure><pre>p3a &lt;- starwars %&gt;%<br>ggplot(aes(x = height, y = 1)) +<br>geom_violin(aes(fill = &quot;blue&quot;),<br>show.legend = F,<br>alpha = .5)+<br>labs(title = &quot;Violin plot&quot;,<br>x = &quot;Height&quot;)<br>print(p3a)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*LtVY3A-FcYB7_1q6tI7Stw.png" /></figure><p><strong><em>Let’s combine all charts in a single displa</em></strong></p><p>To display all charts in a single display, remove the print statement for each chart like print(p1) and others</p><pre>print(p3a)<br>(p1 /p2 | p3 / p3a) +<br>  plot_annotation(title = &quot;Single numeric variable&quot;,<br>                  theme = theme(plot.title = element_text(size = 18,<br>                                                          colour = &quot;blue&quot;))) +<br>  theme(text = element_text(&#39;mono&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*5RrGPQMF-QLd9eU1XYfTnA.png" /></figure><p>To illustrate another concept, consider the example below, which utilizes the gapminder dataset (accessible upon installing the gapminder package). This dataset encompasses five variables, offering a comprehensive view of global data.</p><p>Four of these variables are numeric, representing Gross Domestic Product (GDP) per capita, life expectancy, year, and population size. The fifth variable is categorical, classifying countries into continents. Each numeric variable is linked to a specific aesthetic, while the categorical variable is employed to dissect the data into facets, allowing for a multifaceted exploration of the dataset.</p><pre>gapminder %&gt;%<br>filter(continent %in% c(&quot;Africa&quot;, &quot;Europe&quot;)) %&gt;%<br>filter(gdpPercap &lt; 30000) %&gt;%<br>ggplot(aes(x= gdpPercap,<br>y = lifeExp,<br>size = pop,<br>color = year)) +<br>geom_point() +<br>facet_wrap(~continent) +<br>labs(title = &quot;Life expectancy explained by GDP per capita&quot;,<br>x = &quot;GDP per capita&quot;,<br>y = &quot;Life expectancy&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*v-XRg9Y5FFGH7amWVtUuBw.png" /></figure><p><strong>Bar Chart with Categorical Variables</strong></p><p>In this graphic I’ve included a bar plot for a single categorical variable. If a second categorical variable is added we can disaggregate each bar by either stacking, grouping or presenting a proportion using the second category.</p><pre>p4 &lt;- starwars %&gt;%<br>drop_na(eye_color) %&gt;%<br>filter(eye_color %in% c(&quot;black&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;yellow&quot;)) %&gt;%<br>ggplot(aes(x = eye_color)) +<br>geom_bar(stat = &quot;count&quot;, alpha = 0.5) +<br>labs(title = &quot;Barplot&quot;,<br>x = &quot;Eye colour&quot;,<br>y = &quot;Count&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*XRIoRMBQA69wu7lptXf6dg.png" /></figure><pre>p5 &lt;- starwars %&gt;%<br>drop_na(eye_color, gender) %&gt;%<br>filter(eye_color %in% c(&quot;black&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;yellow&quot;)) %&gt;%<br>ggplot(aes(eye_color, fill = gender)) +<br>geom_bar(stat = &quot;count&quot;, alpha = .5,<br>show.legend = F) +<br>labs(title = &quot;Stacked barplot&quot;,<br>x = &quot;Eye colour&quot;,<br>y = &quot;Count&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*MkompAfbL0-zCkdSWC-9tw.png" /></figure><p>Let’s continue with the chart by changing the code a little and figuring out the big difference.</p><pre>p5a &lt;- starwars %&gt;%<br>drop_na(eye_color, gender) %&gt;%<br>filter(eye_color %in% c(&quot;black&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;yellow&quot;)) %&gt;%<br>ggplot(aes(eye_color, fill = gender)) +<br>geom_bar(stat = &quot;count&quot;, alpha = .5,<br>position=&quot;dodge&quot;,<br>show.legend = F)+<br>labs(title = &quot;Grouped barplot&quot;,<br>x = &quot;Eye colour&quot;,<br>y = &quot;Count&quot;)<br>print(p5a)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Nv-U9O6xxCCMp8U06xtFNg.png" /></figure><pre>p5b &lt;- starwars %&gt;%<br>drop_na(eye_color, gender) %&gt;%<br>filter(eye_color %in% c(&quot;black&quot;, &quot;brown&quot;, &quot;blue&quot;, &quot;yellow&quot;)) %&gt;%<br>ggplot(aes(eye_color, fill = gender)) +<br>geom_bar(stat = &quot;count&quot;, alpha = .5,<br>position=&quot;fill&quot;,<br>show.legend = T) +<br>labs(title = &quot;Percentage barplot&quot;,<br>x = &quot;Eye colour&quot;,<br>y = &quot;Count&quot;) +<br>theme(legend.position = &quot;bottom&quot;)<br>((p4 | p5)/( p5a | p5b)) +<br>plot_annotation(title = &quot;One or more categorical variable&quot;,<br>theme = theme(plot.title = element_text(size = 18,<br>colour = &quot;blue&quot;))) +<br>theme(text = element_text(&#39;mono&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*rXUUuCSc4pfmaztxo8WWWA.png" /></figure><p><strong>Lolipop graphic</strong></p><p>Instead of plotting a simple boxplot for each of the categories,in this example I’ve plotted individual data points of dataset chickwts, the average for each category and then joined the average with a line that represents the average for the entire dataset. To learn more about the data write</p><p>?chickwts</p><p>View(chickwts)</p><p>head(chickwts)</p><pre>chickwts %&gt;%<br>group_by(feed) %&gt;%<br>mutate(mean_by_feed = mean(weight)) %&gt;%<br>ungroup() %&gt;%<br>mutate(feed = fct_reorder(feed, mean_by_feed)) %&gt;%<br>ggplot(aes(feed, weight, colour = feed,<br>show.legend = F)) +<br>coord_flip() +<br>geom_jitter(show.legend = F,<br>size = 4,<br>alpha = 0.2,<br>width = 0.05) +<br>stat_summary(fun = mean, geom = &quot;point&quot;, size = 8, show.legend = F) +<br>geom_hline(aes(yintercept = mean(weight)),<br>colour = &quot;gray70&quot;,<br>size = 0.9) +<br>geom_segment(aes(x = feed, xend = feed,<br>y = mean(weight), yend = mean_by_feed),<br>size = 2, show.legend = F) +<br>labs(title = &quot;Weight of chickens by feed group&quot;,<br>x = &quot;Feed&quot;,<br>y = &quot;Weight of chickens&quot;) +<br>theme(legend.position = &quot;none&quot;) +<br>theme_bw()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*VvQ0RRbPPUCQibnJ7PP5sQ.png" /></figure><p><strong>Using Ridges</strong></p><p>In this visualization I’ve shown distribution of temperatures that occurred within a given month (as a density plot) and then compared each month by plotting the density plots of each month on the same canvas.</p><pre>ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, <br>                            y = `Month`, fill = ..x..)) +<br>  geom_density_ridges_gradient(scale = 3, <br>                               rel_min_height = 0.01,<br>                               alpha = 5) +<br>  scale_fill_viridis(name = &quot;Temp. [F]&quot;, option = &quot;C&quot;) +<br>  labs(title = &#39;Temperatures in Lincoln NE in 2016&#39;) +<br>  theme_bw() +<br>  theme(<br>    legend.position=&quot;none&quot;,<br>    panel.spacing = unit(0.1, &quot;lines&quot;),<br>    strip.text.x = element_text(size = 8)<br>  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*MYngftDRvqEEWa-jOPsZyQ.png" /></figure><p><strong>Unlocking Insights Through Visualization in R</strong></p><p>Data visualization in R is a powerful ally in the realm of data analysis. It empowers us to transform data into actionable insights, making complex information accessible and comprehensible. In this blog post, we explored the significance of data visualization and how R simplifies the creation of diverse chart types, including bar charts, histograms, and density plots.</p><p>Bar charts serve as the cornerstone for comparing categorical data, while histograms reveal the underlying distribution of numeric variables. These charts are easily created and customized in R, thanks to the ggplot2 library’s user-friendly syntax and versatility.</p><p>For a more refined understanding of data distribution, density charts step in, providing smoothed representations that uncover hidden patterns. R’s ggplot2 empowers users to layer visual elements, enhancing the depth and clarity of their visualizations.</p><p>In a world inundated with data, mastering the art of data visualization in R offers a competitive edge. Whether you’re an analyst, a researcher, or a decision-maker, harnessing the power of R’s visualization capabilities can help you extract actionable insights from your data, enabling data-driven decision-making and impactful storytelling. So, don’t just crunch numbers visualize them, and let your data tell its own compelling story with the help of R.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863c0fe11de1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Exploration With SQL]]></title>
            <link>https://medium.com/@zainab.mehmood/data-exploration-with-sql-2493cf12ba08?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/2493cf12ba08</guid>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-exploration]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 16:19:44 GMT</pubDate>
            <atom:updated>2023-08-26T16:19:44.356Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of data exploration, SQL emerges as a guiding compass, steering us through complex datasets to reveal invaluable insights. Embark on a journey into the world of sales data, where we harness the power of SQL to uncover hidden patterns and trends that illuminate the path to informed decision-making.</p><p>Our voyage begins with a look at the geographical distribution of sales. Armed with SQL’s capabilities, we set out to understand the revenue contributions of different regions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WbnEHXHJM5UCDh1KyrrxDw.jpeg" /></figure><pre>-- Query to aggregate sales by GeoID<br>SELECT GeoID, SUM(Amount) AS TotalSales<br>FROM sales<br>GROUP BY GeoID;</pre><p>Diving deeper, we combine aggregation functions to gain a comprehensive understanding of sales performance, factoring in both the total and average sales amounts, as well as the sum of sold boxes.</p><pre>-- Query to aggregate sales metrics by GeoID<br>SELECT GeoID, SUM(Amount) AS TotalSales, AVG(Amount) AS AvgSales, SUM(Boxes) AS TotalBoxes<br>FROM sales<br>GROUP BY GeoID;</pre><p>To enrich our insights, we merge the geo table to our sales data, allowing us to correlate sales with specific geographical regions.</p><pre>-- Query to join sales and geo tables for enriched insights<br>SELECT g.geo, SUM(s.Amount) AS TotalSales, AVG(s.Amount) AS AvgSales, SUM(s.Boxes) AS TotalBoxes<br>FROM sales s<br>JOIN geo g ON s.GeoID = g.GeoID<br>GROUP BY g.geo;</pre><p>Expanding our horizon, we delve into the nexus of salespeople, products, and categories. By leveraging joins, we uncover how different teams contribute to sales across various product categories.</p><pre>-- Query to join people, products, and sales tables<br>SELECT pr.category, p.Team, SUM(s.Boxes) AS TotalBoxes, SUM(s.Amount) AS TotalSales<br>FROM sales s<br>JOIN people p ON p.SPID = s.SPID<br>JOIN products pr ON pr.PID = s.PID<br>GROUP BY pr.category, p.Team;</pre><p>Refining our analysis, we focus on actionable insights. By filtering records, we examine sales patterns within specific criteria, revealing nuances that drive strategic decision-making.</p><pre>-- Query to filter and order sales data<br>SELECT pr.product, SUM(s.Amount) AS &#39;Total Amount&#39;<br>FROM sales s<br>JOIN products pr ON pr.PID = s.PID<br>GROUP BY pr.product<br>ORDER BY SUM(s.Amount) DESC<br>LIMIT 10;</pre><p>In the pursuit of understanding temporal trends, we inspect sales throughout the year, spotlighting transactions exceeding $10,000 in 2022.</p><pre>-- Query to analyze high-value transactions in a specific year<br>SELECT SaleDate, Amount<br>FROM sales<br>WHERE Amount &gt; 10000 AND YEAR(SaleDate) = 2022<br>ORDER BY Amount DESC;</pre><p>As we narrow our focus, we delve into micro-sales dynamics, uncovering transactions below $500 aligned with salespeople and products.</p><pre>-- Query to explore micro-level sales insights<br>SELECT s.SaleDate, s.Amount, p.Salesperson, pr.product, p.team<br>FROM sales AS s<br>JOIN people AS p ON p.SPID = s.SPID<br>JOIN products AS pr ON pr.PID = s.PID<br>WHERE s.Amount &lt; 500;</pre><p>Our journey culminates in discerning patterns through the art of categorization. By creating an “Amount Category,” we transform numerical data into insightful labels.</p><pre>-- Query to categorize sales amounts and derive insights<br>SELECT SaleDate, Amount,<br>       CASE <br>           WHEN Amount &lt; 1000 THEN &#39;under 1K&#39;<br>           WHEN Amount &lt; 5000 THEN &#39;under 5K&#39;<br>           WHEN Amount &lt; 10000 THEN &#39;under 10K&#39;<br>           ELSE &#39;10K or more&#39;<br>       END AS &#39;Amount Category&#39;<br>FROM sales;</pre><p>n the world of data exploration, SQL stands as a faithful companion, guiding us through uncharted territories of information. Armed with SQL’s techniques of aggregation, joining, filtering, and categorization, we’ve unearthed valuable narratives from the sales data. These insights empower us to make informed decisions, strategically navigate challenges, and illuminate the path ahead with data-driven confidence</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2493cf12ba08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Data from Tables and Multiple Web Pages]]></title>
            <link>https://medium.com/@zainab.mehmood/scraping-data-from-tables-and-multiple-web-pages-401d5181771?source=rss-8a6354b12a08------2</link>
            <guid isPermaLink="false">https://medium.com/p/401d5181771</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[scrape-data-from-website]]></category>
            <dc:creator><![CDATA[Zainab Mehmood]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 15:47:50 GMT</pubDate>
            <atom:updated>2023-08-26T15:47:50.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Web Scraping for Population and Product Data Using Python</p><p>In the age of information, data holds immense value. Python, with its robust libraries like BeautifulSoup and pandas, offers a powerful toolkit for extracting, organizing, and analyzing data from the web. In this blog post, we’ll explore two examples: extracting population data and fetching product details from e-commerce websites.</p><p><strong>1. Population Data Extraction</strong></p><p>Suppose you’re interested in global population data by country. Python can assist you in gathering this information using web scraping techniques. We’ll use the BeautifulSoup library to navigate and extract data from the HTML structure of a web page.</p><pre>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd<br><br>url = &#39;https://www.worldometers.info/world-population/population-by-country/&#39;<br>response = requests.get(url)<br>soup = BeautifulSoup(response.text, &#39;html.parser&#39;)<br><br>rows = soup.find(&#39;table&#39;, {&#39;id&#39;: &#39;example2&#39;}).find(&#39;tbody&#39;).find_all(&#39;tr&#39;)<br><br>countries_list = []<br>for row in rows:<br>    dic = {}<br>    dic[&#39;Country&#39;] = row.find_all(&#39;td&#39;)[1].text<br>    dic[&#39;Population 2023&#39;] = row.find_all(&#39;td&#39;)[2].text<br>    # ... Extract other data fields similarly<br>    countries_list.append(dic)<br><br>df = pd.DataFrame(countries_list)<br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV_YU3dHU2duI4MmkbLiDg.png" /><figcaption>Output data from worldometers</figcaption></figure><p><strong>2. E-commerce Product Data Fetching</strong></p><p>Web scraping is also a powerful tool for fetching product details from e-commerce websites. In this example, we’ll scrape product information from Flipkart’s mobile section.</p><pre>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd<br><br>Names = []<br>Prices = []<br>Desc = []<br>Reviews = []<br><br>for i in range(1, 11):<br>    url = &#39;https://www.flipkart.com/search?q=under+50000+price+mobile&amp;otracker=search&amp;otracker1=search&amp;marketplace=FLIPKART&amp;as-show=on&amp;as=off&amp;page=&#39; + str(i)<br>    response = requests.get(url)<br>    <br>    if response.status_code == 200:<br>        soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br>        boxes = soup.find_all(&#39;div&#39;, class_=&#39;_2kHMtA&#39;)<br>        <br>        for box in boxes:<br>            name = box.find(&#39;div&#39;, class_=&#39;_4rR01T&#39;).text<br>            price = box.find(&#39;div&#39;, class_=&#39;_30jeq3&#39;).text<br>            desc = box.find(&#39;ul&#39;, class_=&#39;_1xgFaf&#39;).text<br>            review = box.find(&#39;div&#39;, class_=&quot;_3LWZlK&quot;).text<br>            <br>            Names.append(name)<br>            Prices.append(price)<br>            Desc.append(desc)<br>            Reviews.append(review)<br>    else:<br>        print(&quot;Request failed with status code:&quot;, response.status_code)<br><br>Data = {<br>    &#39;Product Name&#39;: Names,<br>    &#39;Product Price&#39;: Prices,<br>    &#39;Description&#39;: Desc,<br>    &#39;P_Reviews&#39;: Reviews<br>}<br><br>df = pd.DataFrame(Data)<br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*WLqMU6HExFa9LDwRNyWrpg.png" /><figcaption>Product Data scraped from flipkart</figcaption></figure><p>Python’s web scraping capabilities empower you to harness data from diverse sources, enabling you to analyze and gain insights for various purposes. Whether it’s extracting population statistics or gathering e-commerce product details, Python’s versatility offers endless possibilities in the realm of data collection and analysis.</p><p>Feel free to customize the blog post to your liking and add any additional details or insights as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401d5181771" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>