<?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 Ula Yousef on Medium]]></title>
        <description><![CDATA[Stories by Ula Yousef on Medium]]></description>
        <link>https://medium.com/@engulayousef99?source=rss-6874d89de1da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3nEkmuYUOLz2iSHF</url>
            <title>Stories by Ula Yousef on Medium</title>
            <link>https://medium.com/@engulayousef99?source=rss-6874d89de1da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:43:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@engulayousef99/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[Analysis The Gap Between Job Seekers And Employers In Syria.]]></title>
            <link>https://medium.com/@engulayousef99/analysis-the-gap-between-job-seekers-and-employers-in-syria-c90e95d178e2?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90e95d178e2</guid>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 20:46:19 GMT</pubDate>
            <atom:updated>2026-11-22T20:47:47.682Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why do Information Technology Engineering graduates and hiring companies struggle to connect in Syria?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2ybWqsR7ylEtKC0kDVV6A.png" /><figcaption>image from Pixabay</figcaption></figure><p>In late 2024, I conducted a data analysis study on the Syrian IT job market, surveying Informatics Engineering students and graduates to find out where the real disconnect between talent and opportunity lies.</p><h3>But why:</h3><p><strong>Informatics engineering graduates and students are looking for work, and companies are offering jobs. However, </strong>the two sides <strong>fail to connect due to a gap in the academic sector and university curriculum on one hand, workplace culture — represented by the style of job postings — on the other, and the economic situation alongside infrastructure on another.</strong></p><p>This study confirms that a lack of skills and qualifications among job seekers — whether students or graduates — is not the only root problem behind their inability to integrate into the job market. Both suitable opportunities and qualified candidates exist, yet the way these opportunities are advertised and the tools used sometimes create a barrier between them.</p><h3><strong>Scope &amp; Methodology:</strong></h3><p><strong>The study was conducted in late 2024 through a survey designed specifically to target the Syrian IT job market.</strong></p><p><strong>Purposive &amp; Niche Sample:</strong> This study does not represent a general survey of Syrian society; rather, it targets a closed, specialized sample consisting exclusively of Informatics Engineers and students from the Faculty of Informatics Engineering — divided between those currently employed and those seeking job opportunities within the IT sector.</p><p><strong>Trend Stability:</strong> Although the sample is exploratory due to the specialized nature of the target group, the data revealed high recurrence in specific areas — such as oversaturation in web development specializations and barriers related to a lack of salary transparency in job postings. This indicates that increasing the number of responses would not alter the core trajectory or trends of the IT job market, even if exact percentages were to shift slightly.</p><p><strong>Software Architecture:</strong> The data was processed using scalable Python pipelines, leaving the system well-equipped to accommodate a larger volume of responses in the future.</p><h3><strong>Study Participant Demographics:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IonSebdGnDTeevD2BHtuVQ.png" /></figure><p>percentage of graduates: 47.1%, percentage of students: 52.9%.</p><p>percentage of male: 58.6%, percentage of female: 41.4%.</p><h3>Academic Background and Workforce Integration:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*DNEyghCV798wU68OSNKRng.png" /></figure><p>percentage of employees: 42.9%, percentage of jobseekers: 57.1%.</p><p>percentage of Artificial Intelligence department:47.1%.</p><p>percentage of Software &amp; Information System department: 34.3%.</p><p>percentage of Network &amp; Computer System department: 8.6%.</p><p>percentage of Non-specialized: 10.0%.</p><h3>Demographic Distribution of Employment Status by Age Groups:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Xy7IvOs4skyQViNhOONHSg.png" /></figure><p><strong>Academic Attainment Stage (19–21):</strong> A predominance of economically inactive individuals, as most are focused on university studies.</p><p><strong>Graduation Stage (22):</strong> The peak of unemployment, representing the first point of friction as fresh graduates navigate job market requirements.</p><p><strong>Career Transition Stage (25 and above):</strong> A major shift toward employment compared to previous age groups, indicating that most qualified individuals have developed their skills and secured jobs.</p><h3><strong>Academic Alignment Rate:</strong> The Percentage of Jobs Relevant to a Graduate’s University Major</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*T-uG9bqxHpl-CTzrzPG5aQ.png" /></figure><p>Due to the unequal sample sizes, I analyzed each specialization separately:</p><p><strong>Software Department:</strong> There is a strong alignment between the specialization and the field of work, confirming that it is the most in-demand field in the job market.</p><p><strong>Artificial Intelligence Department:</strong> There is a gap between academic study and the job market, as nearly half of the graduates are forced to pursue careers unrelated to their field.</p><p><strong>Networks Department:</strong> The sample size is small compared to those of other specializations, yet a gap is evident between those working within their field and those who are not</p><h3>Academic Alignment Gap: Career Displacement Relative to University Major.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*FqamBebeixhoviJQgomnMQ.png" /></figure><p><strong>Artificial Intelligence Department:</strong> Although there are professionals working in data science and AI engineering, there is a shift toward web and Android development.</p><p><strong>Networks &amp; Computer Systems Department:</strong> Network engineering dominates, though there is a shift toward other specializations such as web development.</p><p><strong>Software Engineering &amp; Information Systems Department:</strong> Web development accounts for the largest share of the job market.</p><p><strong>Non-specialized (students in their first three years):</strong> Most have chosen web development as their future career path</p><h3>Employment Status in Syria’s Tech Sector:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*0gAnmRfGM9hF0nv2oTS9sg.png" /></figure><p><strong>Unemployment Crisis in the Web Development Sector:</strong> Because almost all graduates enter this field, competition is fierce, making it difficult to secure a job easily.</p><p><strong>Absorption Gap in the Android and Mobile Application Development Sectors:</strong> Companies are struggling to absorb new developers, often due to a lack of practical skills among newcomers. The same applies to the Data Science sector.</p><p><strong>Talent Shortage in the AI Automation and Information Security Sectors:</strong> Despite high demand, there is a lack of qualified job seekers. Because these specializations are rare, anyone who masters them can get hired immediately.</p><h3>Employment Status by Job Title Across Tech Sectors:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*UJUQaiEfyp31bLVCibxesA.png" /></figure><p><strong>Market Saturation:</strong> A large portion of front-end developers are unemployed due to the massive number of applicants competing for the same openings.</p><p><strong>Mobile App Developers</strong> are also experiencing unemployment, despite being far fewer in number than front-end developers. This confirms either the market’s inability to absorb them or constant shifts in required skills.</p><p><strong>Data Scientists and Data Analysts</strong> face career stagnation despite their small numbers. This reflects an infrastructure gap among companies in Syria — such as relying on traditional spreadsheets or basic automation systems to store data — which leaves the strategic importance of these roles largely unrecognized.</p><p><strong>Full-Stack Developers </strong>enjoy high market demand, confirming a strong preference among companies for multi-role professionals</p><h3>The Impact of Assistance and Networking on the Hiring Period:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*pbyZIKLq5IP2Jfdm4WKRyg.png" /></figure><p><strong>Early Employment before Graduation:</strong> Most people who secured a job during this period received assistance, confirming that networking and relationship-building accelerate entry into the job market prior to earning a degree.</p><p><strong>Traditional Employment after Graduation:</strong> The majority of people did not receive such support, relying instead on competence, experience, and individual effort.</p><h3>The Impact of Networking on Unemployment Durations and the Speed of Employment:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*wv5hCQYDbBANkaV8l8anOQ.png" /></figure><p><strong>1-to-3-Month Sample:</strong> The largest portion of those who secured a job within this period — roughly double the other group — received direct assistance.</p><p><strong>4-mMonth-to-1-Year Sample:</strong> Among those who took this long to find a job, the majority relied on their own efforts.</p><p><strong>More-Than-1-Year Sample:</strong> The largest segment in this group received assistance to enter the labor market. This confirms that a professional network helps individuals who have lost their “fresh graduate” advantage, meaning that a long career gap makes relying solely on self-effort insufficient to secure employment.</p><p><strong>Undefined Sample:</strong> Some participants in this category preferred not to disclose how long it took them to find a job</p><h3>Job Hunting Challenges:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Za38b0QUcp_naCAiEvRCSg.png" /></figure><p><strong>Practical Experience Gap:</strong> Lack of experience tops the list of challenges at over 80%, reflecting the struggle fresh graduates face in meeting market requirements and landing their first opportunity.</p><p><strong>Practical Proof and Academic Alignment:</strong> Two critical factors exceed the 50% mark: building a professional portfolio and the gap between university curricula and labor market demands. This confirms that a university degree alone is no longer enough to secure a job.</p><p><strong>Career Guidance and Language Challenges:</strong> Obstacles such as defining a career path, English language proficiency, and proximity to the workplace rank in the middle tier (25%–35%).</p><p><strong>Structural and Social Factors:</strong> Mandatory military service and a weak work culture account for the lowest percentages on the list.</p><h3>Reasons Why Top Talent Avoids Job Advertisements:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*5xPKAa19YFwMIPwTCrKuvg.png" /></figure><p><strong>Unrealistic Experience Requirements:</strong> Demanding extensive years of experience tops the list of factors deterring talent — by a margin exceeding 70% — across all career levels (junior, mid-level, and senior).</p><p><strong>Financial Transparency and Company Identity:</strong> Low salaries and a lack of basic company information rank second and third, reflecting job seekers’ hesitation to apply to unknown entities or financially unrewarding opportunities.</p><p><strong>Ambiguity and Wage Concealment (40%–45%):</strong> A significant portion of job seekers avoids job postings with vague job titles or those that withhold salary ranges.</p><p><strong>Job Description Phrasing and Work Culture:</strong> Factors such as overly lengthy job descriptions and a failure to highlight career growth and internal work culture deter roughly one-third of candidates from engaging with a job posting.</p><h3>Obstacles During the Job Search vs. Facilitating Factors for Employment:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*rMNZ5Vz56-2Vbs6W92kmmQ.png" /></figure><p><strong>Networking as an Alternative to Experience (The Great Paradox):</strong> While a lack of experience tops the list of obstacles (80%), having a network within the target company emerges as the most important factor in landing a job (68.57%). This proves that professional connections act as the real bridge to overcoming experience requirements.</p><p><strong>Building a Portfolio (Second Place):</strong> A decisive shared factor, acting both as a barrier to getting hired when missing and a key enabler for employment.</p><p><strong>Soft Skills Outweigh Certificates:</strong> Presenting oneself professionally in job interviews (61.34%) and having strong communication and teamwork skills (55.71%) rank significantly higher than obtaining training course certificates (34.29%) and academic excellence (27.14%). This confirms that the tech job market evaluates a candidate’s practical performance rather than paper credentials.</p><p><strong>The Importance of English Proficiency:</strong> Although language proficiency poses a moderately significant barrier (27.14%), achieving a strong command of English serves as a major competitive advantage for getting hired (55.71%).</p><h3>Career and Employment Challenges for Master’s and PhD Students:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*2jx7cqj1VzhyxxmsCofAtw.png" /></figure><p><strong>Full-Time Work (The Biggest Obstacle):</strong> Companies requiring full-time employment pose the most prominent challenge for graduate students, as it limits their ability to balance job commitments with scientific research requirements.</p><p><strong>Conflicting Work Schedules:</strong> The clash between traditional working hours and university obligations (grading, proctoring, and lecturing) stands out as a second major barrier, reflecting the need for more flexible work arrangements or remote work options for this demographic.</p><p><strong>Lack of Part-Time Opportunities:</strong> The absence of part-time jobs and the difficulty of balancing professional and academic tasks rank equally, placing researchers in a challenging position where they must choose between their academic and career paths.</p><p><strong>Weak Ecosystem for Applied Research:</strong> This obstacle reflects the lack of work environments that invest in the advanced research skills of graduate students and translate them into technological products for the labor market.</p><h3>Strategic Recommendations for Students and Graduates:</h3><p><strong>Breaking Away From Oversaturated Fields and Pivoting Toward Specialized Niches:</strong> Move away from fierce competition in crowded areas like front-end development, and invest in high-demand, scarce specializations in the local market — such as AI automation, information security, or multidisciplinary roles like full-stack development.</p><p><strong>Investing in Networking and a Strong Portfolio:</strong> Overcome the lack of practical experience — which represents the biggest barrier at 80% — by building a strong, hands-on portfolio that proves real competence. Actively engage in professional networking before graduation, as it is the primary key to landing a first job faster.</p><p><strong>Developing Soft Skills and Language Proficiency:</strong> Focus on communication, teamwork, and presenting yourself professionally in interviews. Alongside this, improve your English proficiency as a competitive advantage that outweighs accumulating theoretical course certificates.</p><h3>Strategic recommendations: for Tech Companies and Employers:</h3><p><strong>Re-engineering Job Postings (Transparency and Clarity):</strong> Stop posting vague job ads or setting impossible experience requirements for entry-level candidates; commit to disclosing approximate salary ranges, a clear overview of the company and its culture, and precise job responsibilities to prevent alienating over 60% of top talent.</p><p><strong>Creating Flexible Work Arrangements for Researchers:</strong> Provide part-time or remote roles for postgraduate students (Master’s and PhD) to leverage their advanced research skills in developing innovative tech products without conflicting with their academic commitments.</p><p><strong>Leveraging Data in Decision-Making:</strong> Begin establishing modern data management infrastructure within companies, and empower Data Analysts and Data Scientists to utilize available market talent and transform raw data into economic value.</p><p><strong>Building Research Partnerships with Universities to Establish R&amp;D Units:</strong> Create a work environment that invests in the specialized expertise of postgraduate students, subsequently transforming their theses into tech products for the Syrian labor market.</p><h3>Strategic Recommendations: for Academic Institutions and Universities:</h3><p><strong>Updating Curriculum and Linking Them to the Labor Market:</strong> Bridging the gap between theoretical courses and tech company requirements (highlighted by over 54% of participants) by introducing practical projects that simulate real-world work environments and adopting the latest in-demand technologies.</p><p><strong>Establishing Career Guidance Centers and Business Incubators:</strong> Creating academic and career counseling units within colleges to guide first-year students toward suitable career paths, while building direct partnerships with private-sector companies to secure internships and pre-graduation job opportunities.</p><p><strong>Developing Incubator Environments and Part-Time University Research Labs:</strong> Linking graduate students’ theses to applied projects that solve real-world problems through practical scientific research.</p><h3><strong>Study Limitations and Future Scope:</strong></h3><p><strong>Imbalanced Classes:</strong> The study showed a higher concentration in the Junior and Mid-Level categories compared to the Senior category and specialized sectors such as networking.</p><p><strong>Avoiding Statistical Bias:</strong> To ensure scientific accuracy and prevent misleading conclusions, an independent relative evaluation was adopted for each specialization. The analysis focused on overall patterns regarding obstacles and talent attrition to avoid drawing generalizations from underrepresented career levels.</p><p><strong>Scalability:</strong> Because the project was built using dynamic data pipelines in Python, the software architecture is fully prepared to accommodate broader, more balanced samples in the future, allowing these cross-comparisons to be conducted with higher accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90e95d178e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Missing Data: Not all Missing Means Nothing, Not all Absences Must Be Imputed With…]]></title>
            <link>https://medium.com/@engulayousef99/handling-missing-data-not-all-missing-means-nothing-not-all-absences-must-be-imputed-with-a2fb6ce019af?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2fb6ce019af</guid>
            <category><![CDATA[missing-values]]></category>
            <category><![CDATA[missing-not-at-random]]></category>
            <category><![CDATA[missing-at-random]]></category>
            <category><![CDATA[carm]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 00:00:21 GMT</pubDate>
            <atom:updated>2026-09-20T09:06:40.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling Missing Data: Not all Missing Means Nothing, Not all Absences Must Be Imputed With Something</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*JNeKsjiJmxZDvzzwmZTHfQ.png" /><figcaption><strong>image made by me</strong></figcaption></figure><p>Hi, I’m Ula, an AI Engineer and Data Scientist who actually enjoys spending hours preprocessing data. Personally, I feel a bit sorry for two kinds of people: first, those who share data insights without doing any cleansing, and second, those who blindly fill every single null value with the mean. <strong>If you want to know why these two habits drive me crazy and how to fix them, let’s dive in.</strong></p><h3><strong>First what are missing values?</strong></h3><p><strong>Missing values: values of variables that didn’t recorded during data collection.</strong></p><h3><em>Types of Missing Values:</em></h3><h4>1. Missing At Random (MAR):</h4><p>The value of one variable is missing depends on the value of another one, so the data is missing only with sub-samples of the data not in all observations. Example: in a survey you may notice there are missing data in number of child variable when the status variable is single.</p><h4>2. Missing Not At Random (MNAR):</h4><p>The probability that a value is missing depends on the unobserved value itself. Example: high earners choose not to report their income because they are uncomfortable sharing their specific financial brackets. The missing depends directly on the value of the income itself</p><h4>3. Missing Completely At Random (MCAR):</h4><p>The probability that a value is missing does not depend on either the observed values or the unobserved values , occurs due to human error, some system/ equipment failure, bad luck. Example someone forget to enter his/ her age while filling a survey.</p><h3>How to handle missing values:</h3><p>There are several ways to handle missing data. Some people think they can use them arbitrarily, which is a big mistake that data analysts make. Before you choose a method, you should study the type of missing data you have and the size of the dataset. You should also check if a correlation between variables can help you understand the missing values.</p><h3>Missing values preprocessing techniques:</h3><h4><strong>1. Remove rows with missing values:</strong></h4><ul><li>Also called listwise deletion.</li><li>easy to apply and efficient.</li><li>Reduce sample size.</li><li>Can lead to biased result.</li></ul><h4>2. Replace missing values with estimated ones (Mean imputation):</h4><ul><li>Replace missing values with the mean or with mean of a specific sup group in the data which contain the missing data.</li><li>Preserves sample size.</li><li>Can lead to bias.</li></ul><h4>3. Replace missing values with estimated ones (Mode imputation):</h4><ul><li>Replace missing values with the most repeated value.</li><li>Preserves sample size.</li><li>Can lead to bias.</li></ul><h4>4. Forward and backward Fill:</h4><ul><li>Replace missing values with the next or previous non missing values in the same column</li><li>Simple &amp; Useful when there are a logical order in the data.</li><li>Example: fillna(method=‘ffill’) ,fillna(method=‘bfill’).</li></ul><h4>5. Interpolation technique:</h4><ul><li>Estimates missing values based on surrounding data point using technique like linear interpolation and spline interpolation.</li><li>This technique is useful when the relation between the data is known and easy to estimate whether it is linear or quadratic.</li></ul><h4>6. Fill in missing data manually:</h4><ul><li>Good for Small datasets<strong>:</strong> If you have only a few rows or missing values, typing them in by hand is quick and easy.</li><li>Known missing facts: If you personally know the exact missing value then manual correction ensures high accuracy.</li></ul><h4>Practical section:</h4><p>we will use SF Salaries from Kaggle, we will explore the data together trying to understand the issues related with missing values.</p><p><strong>Importing libraries:</strong></p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import kagglehub<br>from IPython.display import display</pre><p><strong>Reading data directly from Kaggle:</strong></p><pre><br># Download the latest version of the SF Salaries dataset to temporary cache<br>path = kagglehub.dataset_download(&quot;kaggle/sf-salaries&quot;)<br><br>print(&quot;Dataset cached at:&quot;, path)<br><br># Load the specific CSV file directly into memory<br>df = pd.read_csv(f&quot;{path}/Salaries.csv&quot;, low_memory=False)<br>print(df.head())</pre><p><strong>Output:</strong></p><pre>Using Colab cache for faster access to the &#39;sf-salaries&#39; dataset.<br>Dataset cached at: /kaggle/input/sf-salaries<br>   Id       EmployeeName                                        JobTitle  \<br>0   1     NATHANIEL FORD  GENERAL MANAGER-METROPOLITAN TRANSIT AUTHORITY   <br>1   2       GARY JIMENEZ                 CAPTAIN III (POLICE DEPARTMENT)   <br>2   3     ALBERT PARDINI                 CAPTAIN III (POLICE DEPARTMENT)   <br>3   4  CHRISTOPHER CHONG            WIRE ROPE CABLE MAINTENANCE MECHANIC   <br>4   5    PATRICK GARDNER    DEPUTY CHIEF OF DEPARTMENT,(FIRE DEPARTMENT)   <br><br>     BasePay OvertimePay   OtherPay Benefits   TotalPay  TotalPayBenefits  \<br>0  167411.18         0.0  400184.25      NaN  567595.43         567595.43   <br>1  155966.02   245131.88  137811.38      NaN  538909.28         538909.28   <br>2  212739.13   106088.18    16452.6      NaN  335279.91         335279.91   <br>3    77916.0    56120.71   198306.9      NaN  332343.61         332343.61   <br>4   134401.6      9737.0  182234.59      NaN  326373.19         326373.19   <br><br>   Year  Notes         Agency Status  <br>0  2011    NaN  San Francisco    NaN  <br>1  2011    NaN  San Francisco    NaN  <br>2  2011    NaN  San Francisco    NaN  <br>3  2011    NaN  San Francisco    NaN  <br>4  2011    NaN  San Francisco    NaN</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXXiiENGMQA9JsGve3NwNg.png" /></figure><p><strong>Explore the data:</strong></p><pre>def explore_dataset(data):<br>   print(&quot; 1. data Shape&quot;)<br>   print(f&quot; number of rows: {data.shape[0]} | number of columns : {data.shape[1]}\n&quot;)<br>   print(&quot;2. columns&#39;s info &quot;)<br>   print(data.info())<br>   print(&quot;\n&quot;)    <br>   print(&quot;3. Statistics description of numerical columns&quot;)<br>   print(data.describe())<br>   print(&quot;\n&quot;)<br>   print(&quot;4. name of columns&quot;)<br>   print(list(data.columns))<br>explore_dataset(df)</pre><p><strong>Output:</strong></p><pre> 1. data Shape<br> number of rows: 148654 | number of columns : 13<br><br>2. columns&#39;s info <br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 148654 entries, 0 to 148653<br>Data columns (total 13 columns):<br> #   Column            Non-Null Count   Dtype  <br>---  ------            --------------   -----  <br> 0   Id                148654 non-null  int64  <br> 1   EmployeeName      148654 non-null  object <br> 2   JobTitle          148654 non-null  object <br> 3   BasePay           148049 non-null  object <br> 4   OvertimePay       148654 non-null  object <br> 5   OtherPay          148654 non-null  object <br> 6   Benefits          112495 non-null  object <br> 7   TotalPay          148654 non-null  float64<br> 8   TotalPayBenefits  148654 non-null  float64<br> 9   Year              148654 non-null  int64  <br> 10  Notes             0 non-null       float64<br> 11  Agency            148654 non-null  object <br> 12  Status            38119 non-null   object <br>dtypes: float64(3), int64(2), object(8)<br>memory usage: 14.7+ MB<br>None<br><br><br>3. Statistics description of numerical columns<br>                  Id       TotalPay  TotalPayBenefits           Year  Notes<br>count  148654.000000  148654.000000     148654.000000  148654.000000    0.0<br>mean    74327.500000   74768.321972      93692.554811    2012.522643    NaN<br>std     42912.857795   50517.005274      62793.533483       1.117538    NaN<br>min         1.000000    -618.130000       -618.130000    2011.000000    NaN<br>25%     37164.250000   36168.995000      44065.650000    2012.000000    NaN<br>50%     74327.500000   71426.610000      92404.090000    2013.000000    NaN<br>75%    111490.750000  105839.135000     132876.450000    2014.000000    NaN<br>max    148654.000000  567595.430000     567595.430000    2014.000000    NaN<br><br><br>4. name of columns<br>[&#39;Id&#39;, &#39;EmployeeName&#39;, &#39;JobTitle&#39;, &#39;BasePay&#39;, &#39;OvertimePay&#39;, &#39;OtherPay&#39;, &#39;Benefits&#39;, &#39;TotalPay&#39;, &#39;TotalPayBenefits&#39;, &#39;Year&#39;, &#39;Notes&#39;, &#39;Agency&#39;, &#39;Status&#39;]</pre><p><strong>Note:</strong></p><ul><li>We have many numeric columns whose types have been defined as object, so we need to convert them to numeric types. Also there are string columns whose types have been defined as object.</li><li>Statistic description indicates that there are negative values in TotalPay, TotalPayBenefits, this can be caused by accounting adjustments. When an overpaid employee is issued a corrective adjustment in a subsequent year — and has no other active earnings in that department — the net result for their line item is negative,we can keep those negative amounts, but doing this can be misleading and skew statistical metrics like the mean or standard deviation. The better choice is <strong>to</strong> replace them with zero</li></ul><p><strong>Convert columns type:</strong></p><pre>def convert_type(df):<br>  for col in df.columns:<br>    df[col]=pd.to_numeric(df[col], errors=&#39;ignore&#39;)<br>    df[col]=df[col].convert_dtypes()<br>  return df<br>df=convert_type(df)<br>df.dtypes</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*X7tgEP2WEsbk7RMhSVNFTw.png" /></figure><p>Note: some numerical columns are converted to string ,indicating the presence of string value.</p><p><strong>Unique values of BasePay, Benefits and the other columns to find the string values:</strong></p><pre>def print_unique(df, columns):<br>    df[columns].apply(lambda col: print(f&quot;The unique values of {col.name} are {col.unique()}\n&quot;))<br>columns = df.select_dtypes(include=[&#39;string&#39;]).columns<br>print_unique(df, columns)</pre><p><strong>Output</strong>:</p><pre>The unique values of EmployeeName are &lt;StringArray&gt;<br>[    &#39;NATHANIEL FORD&#39;,       &#39;GARY JIMENEZ&#39;,     &#39;ALBERT PARDINI&#39;,<br>  &#39;CHRISTOPHER CHONG&#39;,    &#39;PATRICK GARDNER&#39;,     &#39;DAVID SULLIVAN&#39;,<br>          &#39;ALSON LEE&#39;,      &#39;DAVID KUSHNER&#39;,     &#39;MICHAEL MORRIS&#39;,<br> &#39;JOANNE HAYES-WHITE&#39;,<br> ...<br>  &#39;Brieanna Mcfadden&#39;,  &#39;Trayvonte T Britt&#39;,      &#39;Randall Cinti&#39;,<br>     &#39;Tucker L Silva&#39;,  &#39;Afakasi O Afakasi&#39;,     &#39;Kenneth Mackey&#39;,<br>     &#39;Mark W Mcclure&#39;, &#39;Charlene D Mccully&#39;,       &#39;Not provided&#39;,<br>          &#39;Joe Lopez&#39;]<br>Length: 110811, dtype: string<br><br>The unique values of JobTitle are &lt;StringArray&gt;<br>[  &#39;GENERAL MANAGER-METROPOLITAN TRANSIT AUTHORITY&#39;,<br>                  &#39;CAPTAIN III (POLICE DEPARTMENT)&#39;,<br>             &#39;WIRE ROPE CABLE MAINTENANCE MECHANIC&#39;,<br>     &#39;DEPUTY CHIEF OF DEPARTMENT,(FIRE DEPARTMENT)&#39;,<br>                        &#39;ASSISTANT DEPUTY CHIEF II&#39;,<br>               &#39;BATTALION CHIEF, (FIRE DEPARTMENT)&#39;,<br>                   &#39;DEPUTY DIRECTOR OF INVESTMENTS&#39;,<br>           &#39;CHIEF OF DEPARTMENT, (FIRE DEPARTMENT)&#39;,<br> &#39;ASSISTANT CHIEF OF DEPARTMENT, (FIRE DEPARTMENT)&#39;,<br>                      &#39;EXECUTIVE CONTRACT EMPLOYEE&#39;,<br> ...<br>                      &#39;Hospital Eligibility Worker&#39;,<br>                                &#39;Personnel Trainee&#39;,<br>                      &#39;ACPO,JuvP, Juv Prob (SFERS)&#39;,<br>                        &#39;Apprentice Cement Mason I&#39;,<br>                         &#39;Marina Associate Manager&#39;,<br>                     &#39;Sr Cnselor, Juv Hall (SFERS)&#39;,<br>                   &#39;Forensic Toxicologist Supervis&#39;,<br>                                       &#39;Conversion&#39;,<br>                                        &#39;Cashier 3&#39;,<br>                                     &#39;Not provided&#39;]<br>Length: 2159, dtype: string<br><br>The unique values of BasePay are &lt;StringArray&gt;<br>[   &#39;167411.18&#39;,    &#39;155966.02&#39;,    &#39;212739.13&#39;,      &#39;77916.0&#39;,<br>     &#39;134401.6&#39;,     &#39;118602.0&#39;,     &#39;92492.01&#39;,    &#39;256576.96&#39;,<br>    &#39;176932.64&#39;,     &#39;285262.0&#39;,<br> ...<br>        &#39;31.43&#39;,        &#39;21.76&#39;,        &#39;26.94&#39;,        &#39;21.22&#39;,<br>        &#39;19.97&#39;,        &#39;21.48&#39;,        &#39;17.26&#39;,         &#39;6.04&#39;,<br>        &#39;15.50&#39;, &#39;Not Provided&#39;]<br>Length: 109725, dtype: string<br><br>The unique values of OvertimePay are &lt;StringArray&gt;<br>[         &#39;0.0&#39;,    &#39;245131.88&#39;,    &#39;106088.18&#39;,     &#39;56120.71&#39;,<br>       &#39;9737.0&#39;,       &#39;8601.0&#39;,      &#39;89062.9&#39;,     &#39;86362.68&#39;,<br>     &#39;71344.88&#39;,     &#39;87082.62&#39;,<br> ...<br>       &#39;292.13&#39;,       &#39;285.00&#39;,       &#39;277.88&#39;,       &#39;293.44&#39;,<br>       &#39;113.54&#39;,       &#39;249.42&#39;,       &#39;228.00&#39;,       &#39;102.70&#39;,<br>        &#39;56.77&#39;, &#39;Not Provided&#39;]<br>Length: 66162, dtype: string<br><br>The unique values of OtherPay are &lt;StringArray&gt;<br>[   &#39;400184.25&#39;,    &#39;137811.38&#39;,      &#39;16452.6&#39;,     &#39;198306.9&#39;,<br>    &#39;182234.59&#39;,    &#39;189082.74&#39;,    &#39;134426.14&#39;,      &#39;51322.5&#39;,<br>     &#39;40132.23&#39;,     &#39;17115.73&#39;,<br> ...<br>        &#39;52.59&#39;,        &#39;43.50&#39;,        &#39;33.55&#39;,        &#39;39.91&#39;,<br>        &#39;25.57&#39;,        &#39;19.81&#39;,        &#39;10.05&#39;,        &#39;15.35&#39;,<br> &#39;Not Provided&#39;,      &#39;-618.13&#39;]<br>Length: 84243, dtype: string<br><br>The unique values of Benefits are &lt;StringArray&gt;<br>[          &lt;NA&gt;,     &#39;44430.12&#39;,     &#39;69810.19&#39;,     &#39;53102.29&#39;,<br>     &#39;72047.88&#39;,     &#39;44438.25&#39;,     &#39;84681.82&#39;,     &#39;82001.94&#39;,<br>     &#39;81824.37&#39;,     &#39;24287.23&#39;,<br> ...<br>         &#39;0.32&#39;,         &#39;0.31&#39;,         &#39;0.27&#39;,         &#39;4.99&#39;,<br>         &#39;4.30&#39;,         &#39;0.22&#39;,         &#39;2.30&#39;,         &#39;0.13&#39;,<br>         &#39;1.24&#39;, &#39;Not Provided&#39;]<br>Length: 98648, dtype: string</pre><p>The values in the JobTitle column are inconsistent, appearing in both uppercase and lowercase, so we will unify them all to lowercase.</p><pre>def convert_to_lower(df):<br>  df=df.str.lower()<br>  print(df.unique())<br>  return df<br>df[&#39;JobTitle&#39;]=convert_to_lower(df[&#39;JobTitle&#39;])</pre><p><strong>Output:</strong></p><pre>&lt;StringArray&gt;<br>[  &#39;general manager-metropolitan transit authority&#39;,<br>                  &#39;captain iii (police department)&#39;,<br>             &#39;wire rope cable maintenance mechanic&#39;,<br>     &#39;deputy chief of department,(fire department)&#39;,<br>                        &#39;assistant deputy chief ii&#39;,<br>               &#39;battalion chief, (fire department)&#39;,<br>                   &#39;deputy director of investments&#39;,<br>           &#39;chief of department, (fire department)&#39;,<br> &#39;assistant chief of department, (fire department)&#39;,<br>                      &#39;executive contract employee&#39;,<br> ...<br>                             &#39;special assistant 11&#39;,<br>                                &#39;personnel trainee&#39;,<br>                      &#39;acpo,juvp, juv prob (sfers)&#39;,<br>                        &#39;apprentice cement mason i&#39;,<br>                         &#39;marina associate manager&#39;,<br>                     &#39;sr cnselor, juv hall (sfers)&#39;,<br>                   &#39;forensic toxicologist supervis&#39;,<br>                                       &#39;conversion&#39;,<br>                                        &#39;cashier 3&#39;,<br>                                     &#39;not provided&#39;]<br>Length: 1637, dtype: string</pre><p>The value Not Provided’ appears for BasePay, OvertimePay, OtherPay, and Benefits. Let’s find its location</p><pre>print(&quot;The location where Benefits = Not Provided&quot;,&quot;The index is&quot;,df.loc[df[&#39;Benefits&#39;]==&#39;Not Provided&#39;].index)<br>display(df.loc[df[&#39;Benefits&#39;]==&#39;Not Provided&#39;])<br>print(&quot;The location where OvertimePay = Not Provided&quot;,&quot;The index is&quot;,df.loc[df[&#39;OvertimePay&#39;]==&#39;Not Provided&#39;].index)<br>display(df.loc[df[&#39;OvertimePay&#39;]==&#39;Not Provided&#39;])<br>print(&quot;The location where OtherPay = Not Provided&quot;,&quot;The index is&quot;,df.loc[df[&#39;OtherPay&#39;]==&#39;Not Provided&#39;].index)<br>display(df.loc[df[&#39;OtherPay&#39;]==&#39;Not Provided&#39;])<br>print(&quot;The location where BasePay = Not Provided&quot;,&quot;The index is&quot;,df.loc[df[&#39;BasePay&#39;]==&#39;Not Provided&#39;].index)<br>display(df.loc[df[&#39;BasePay&#39;]==&#39;Not Provided&#39;])</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5b7Wp4lNkhhMWhZagZXCZw.png" /></figure><p>The output shows that when the values of any: BasePay, OvertimePay, OtherPay, and Benefits columns are Not Provided, the other values in the same sample are NaN or Not Provided or 0. Therefore, we will drop the samples that meet this condition by dropping their indices.</p><p><strong>You can drop these samples by passing their index:</strong></p><pre>def drop_samples_by_index(indices):<br>    return df.drop(index=indices, inplace=True)<br>df=df.drop(index=[148646,148650,148651,148652])</pre><p><strong>Call the convert_type function to change BasePay, Benefits, OvertimePay, OtherPay to numerical type after deleting string values:</strong></p><pre>df=convert_type(df)<br>df.dtypes</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*xxEDP7WFFg9HcGBIdKnBhA.png" /></figure><p><strong>Replace Negative values with zero:</strong></p><pre>def convert_negative(df):<br>    for col in df.columns:<br>      if df[col].dtype!=&#39;string&#39;:<br>        df[col] = df[col].clip(lower=0)<br>    return df<br>df = convert_negative(df)<br>df.describe()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*MHVclS7O6iOAOedHz2aiRw.png" /></figure><p><strong>Check for null values and duplicated:</strong></p><pre>def check_data(df):<br>  print(&quot;Null values are:&quot;)<br>  print(df.isnull().sum())<br>  print(&quot;\n&quot;)<br>  print(&quot;duplicated samples are:&quot;)<br>  print(df.duplicated().sum())<br>check_data(df)</pre><p><strong>Output:</strong></p><pre>Null values are:<br>Id                       0<br>EmployeeName             0<br>JobTitle                 0<br>BasePay                605<br>OvertimePay              0<br>OtherPay                 0<br>Benefits             36159<br>TotalPay                 0<br>TotalPayBenefits         0<br>Year                     0<br>Notes               148654<br>Agency                   0<br>Status              110535<br>dtype: int64<br><br><br>duplicated samples are:<br>0</pre><p><strong>Note:</strong></p><ol><li>The number of null values in Notes column are 148654 = number of rows in the data, those values are missing completely at random because it is structurally blank across the entire dataset, the reason the data is missing has absolutely no relationship with the values themselves (MNAR) or with any other observed variables in the dataset like JobTitle or BasePay (MAR) → drop the column.</li><li>The number of null values in Status column is 110535, to figure out if those missing are MAR, MNAR,MCAR, we will check them according to the year in which the specific payroll data were recorded for each employee</li><li>The number of missing values in BasePay column are 605.</li><li>The number of missing values in Benefits column are 36159.</li></ol><p><strong>Check for the year for missing and non-missing values in the Status column:</strong></p><pre>print(&quot;The year of non_missing values of Status are:&quot;,df.loc[df[&#39;Status&#39;].isnull()==False,&#39;Year&#39;].unique())<br>print(&quot;The year of missing values of Status are:&quot;,df.loc[df[&#39;Status&#39;].isnull()==True,&#39;Year&#39;].unique())</pre><p><strong>Output:</strong></p><pre>The year of non_missing values of Status are: &lt;IntegerArray&gt;<br>[2014]<br>Length: 1, dtype: Int64<br>The year of missing values of Status are: &lt;IntegerArray&gt;<br>[2011, 2012, 2013]<br>Length: 3, dtype: Int64</pre><p>The output shows that missing values in the Status column are <strong>Missing at Random (MAR)</strong> because the probability of the data being missing is directly related to the value of another observed variable (<strong>Year</strong>). Status was not tracked or populated for older years (specifically 2011–2013); tracking started in 2014, meaning the absence of data is systematic and tied to how the data was collected over time. Because more than 74% of the Status column is missing, it is best to drop the column</p><p><strong>Drop columns: Notes, Status, Id, Agency ( Agency has the same value for all samples)</strong></p><pre>def drop_column(df, columns):<br>  return df.drop(columns=columns)<br>columns = [&quot;Id&quot;, &quot;Notes&quot;, &quot;Status&quot;, &quot;Agency&quot;]<br>df = drop_column(df, columns)</pre><p><strong>Find where Benefits has NAN values:</strong></p><pre>df.loc[df[&#39;Benefits&#39;].isnull()==True]</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtsN9rC4lH_s40TlUbMHyA.png" /></figure><p>Looking at dataframe we find that:</p><ol><li>TotalPay is the sum of BasePay, OvertimePay, OtherPay.</li><li>TotalPayBenefits is the sum of TotalBay and Benefits.</li><li>When Benefits has NaN value the TotalPay is equal to TotalPayBenefits →Benefits is equal to zero.</li><li>It seems that benefits missing values appear in 2011, we will check for the year for missing to prove that</li></ol><p><strong>First: check for the year for missing and non-missing values in the Benefits column:</strong></p><pre>print(&quot;The year of non_missing values of Benefits are:&quot;,df.loc[df[&#39;Benefits&#39;].isnull()==False,&#39;Year&#39;].unique())<br>print(&quot;The year of missing values of Benefits are:&quot;,df.loc[df[&#39;Benefits&#39;].isnull()==True,&#39;Year&#39;].unique())</pre><p><strong>Output:</strong></p><pre>The year of non_missing values of Benefits are: &lt;IntegerArray&gt;<br>[2012, 2013, 2014]<br>Length: 3, dtype: Int64<br>The year of missing values of Benefits are: &lt;IntegerArray&gt;<br>[2011]<br>Length: 1, dtype: Int64</pre><p>Note: missing values in the Benefits column are entirely concentrated in the year 2011 → missing values in the Benefits column are <strong>Missing at Random (MAR)</strong> because the probability of the data being missing is directly related to the value of another observed variable (<strong>Year</strong>). Benefits was not tracked in 2011.</p><p><strong>Second: verify the validity of statement (</strong>When Benefits has NaN value the TotalPay is equal to TotalPayBenefits) <strong>, we will test it mathematically using the np.isclose method:</strong></p><pre>def check_pay_formula(df, cols):<br>    col_0, col_1, col_2, col_3, col_4, col_5 = cols<br>    df_filled = df.copy()<br><br>    # Verify TotalPay calculation<br>    total_pay = df_filled[col_0].fillna(0) + df_filled[col_1].fillna(0) + df_filled[col_2].fillna(0)<br>    is_total_pay_correct = np.isclose(df_filled[col_3].fillna(0) , total_pay, atol=0.01,equal_nan=True)<br>    # Verify TotalPayBenefits calculation<br>    benefits_total = df_filled[col_3].fillna(0) + df_filled[col_4].fillna(0)<br>    is_benefits_total_correct = np.isclose(df_filled[col_5].fillna(0) , benefits_total, atol=0.01,equal_nan=True)<br>    print(f&quot;TotalPay formula accuracy:{is_total_pay_correct.mean()*100:.3f}%&quot;)<br>    print(f&quot;TotalPayBenefits formula accuracy:{is_benefits_total_correct.mean()*100:.3f}%&quot;)<br>    return is_total_pay_correct, is_benefits_total_correct<br><br>is_total_pay_correct, is_benefits_total_correct = check_pay_formula(df, [&#39;BasePay&#39;, &#39;OvertimePay&#39;, &#39;OtherPay&#39;, &#39;TotalPay&#39;, &#39;Benefits&#39;, &#39;TotalPayBenefits&#39;])<br>is_total_pay_correct, is_benefits_total_correct</pre><p><strong>Output:</strong></p><pre>TotalPay formula accuracy:99.990%<br>TotalPayBenefits formula accuracy:99.999%<br>(array([ True,  True,  True, ...,  True,  True,  True]),<br> array([ True,  True,  True, ...,  True,  True,  True]))</pre><p>Accuracy: 99.99% →imputing Benefits null values with 0 based on assumption.</p><pre>def impute_Benefits(cols):<br>    Benefits = cols[0]<br>    TotalPayBenefits = cols[1]<br>    TotalPay = cols[2]<br>    if pd.isnull(Benefits):<br><br>        if TotalPayBenefits == TotalPay :<br>            return 0.0<br>    else:<br>        return Benefits<br>df[&#39;Benefits&#39;] = df[[&#39;Benefits&#39;,&#39;TotalPayBenefits&#39;,&#39;TotalPay&#39;]].apply(impute_Benefits,axis=1)<br>print(df[&#39;Benefits&#39;].isnull().sum())</pre><p><strong>Output:</strong></p><pre>0</pre><p><strong>Find where BasePay has NAN values:</strong></p><pre>df.loc[df[&#39;BasePay&#39;].isnull()==True]</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EMGTXoRFuejPzcN4ySgPw.png" /></figure><p>Looking at previous dataframe we notice the following:</p><ol><li>TotalBay is the sum of BasePay, OvertimePay, OtherPay.</li><li>TotalPayBenefits is the sum of TotalBay and Benefits.</li><li>When BasePay has NaN value the OvertimePay is equal to zero and TotalPay is equal to OtherPay → we can impute BasePay with zero.</li><li>It seems that BasePay missing values appear in 2013, we will check for the year for missing to prove that</li></ol><p><strong>First: check for the year for missing and non-missing values in the BasePay column:</strong></p><pre>print(&quot;The year of non_missing values of BasePay are:&quot;,df.loc[df[&#39;BasePay&#39;].isnull()==False,&#39;Year&#39;].unique())<br>print(&quot;The year of missing values of BasePay are:&quot;,df.loc[df[&#39;BasePay&#39;].isnull()==True,&#39;Year&#39;].unique())</pre><p><strong>Output</strong>:</p><pre>The year of non_missing values of BasePay are: &lt;IntegerArray&gt;<br>[2011, 2012, 2013, 2014]<br>Length: 4, dtype: Int64<br>The year of missing values of BasePay are: &lt;IntegerArray&gt;<br>[2013]<br>Length: 1, dtype: Int64</pre><p>Note: missing values in the BasePay column are entirely concentrated in 2013 but also there are non missing values in 2013.</p><p><strong>How can we determine if there is a relationship between these missing values and other features in the same year?</strong></p><p>I will split the data into two subsets: one with missing BasePay in 2013 and one with non_missing BasePay in 2013, then compare the unique values for categorical columns and means for numerical ones in both of them, if there is no shared unique values or there is significant differenced between the mean → there is relationship between some features values and missing values of BasePay → missing values are MAR type.</p><p>If the percentages of unique values are nearly identical across both subsets or there is no significance difference between the means → there is no relationship between any features values and missing values of BasePay → missing values are MCAR type.</p><pre>missing_2013 = df[(df[&#39;Year&#39;] == 2013) &amp; (df[&#39;BasePay&#39;].isna())]<br>not_missing_2013 = df[(df[&#39;Year&#39;] == 2013) &amp; (df[&#39;BasePay&#39;].notnull())]<br>categorical_cols = [&#39;JobTitle&#39;]<br>numerical_cols = [&#39;OvertimePay&#39;, &#39;OtherPay&#39;, &#39;Benefits&#39;, &#39;TotalPay&#39;, &#39;TotalPayBenefits&#39;]<br><br>print(&quot;Categorical columns analysis &quot;)<br>for col in categorical_cols:<br>  unique_missing = set(missing_2013[col].unique())<br>  unique_not_missing = set(not_missing_2013[col].unique())<br>  shared = unique_missing.intersection(unique_not_missing)<br>  unshared = unique_missing - unique_not_missing<br>  print(f&quot;Column &#39;{col}&#39; has {len(shared)} shared unique values.&quot;)<br>  print(f&quot;Column &#39;{col}&#39; has {len(unshared)} unshared unique values.&quot;)<br>  if len(unshared) &gt; 0:<br>   print(f&quot;unshared values: {list(unshared)}\n&quot;)<br><br>print(&quot;Numerical columns analysis&quot;)<br>for col in numerical_cols:<br>  mean_missing = missing_2013[col].fillna(0).mean()<br>  mean_not_missing = not_missing_2013[col].fillna(0).mean()<br>  mean_diff= mean_missing - mean_not_missing<br>  print(f&quot; Column &#39;{col}&#39;:&quot;)<br>  print(f&quot; Mean  in Missing Group:{mean_missing:,.2f}&quot;)<br>  print(f&quot; Mean in Non Missing Group:{mean_missing:,.2f}&quot;)<br>  print(f&quot; Mean  Difference: {mean_diff:.1f}\n&quot;)</pre><p><strong>Output:</strong></p><pre>Categorical columns analysis <br>Column &#39;JobTitle&#39; has 216 shared unique values.<br>Column &#39;JobTitle&#39; has 10 unshared unique values.<br>unshared values: [&#39;recreation director&#39;, &#39;drug court coordinator&#39;, &#39;senior assessment clerk&#39;, &#39;captain, (fire department)&#39;, &#39;public safety comm tech&#39;, &#39;assistant recreation director&#39;, &#39;senior data entry operator&#39;, &#39;is operator-journey&#39;, &#39;is technician assistant&#39;, &#39;head photographer&#39;]<br><br>Numerical columns analysis<br> Column &#39;OvertimePay&#39;:<br> Mean  in Missing Group:5.39<br> Mean in Non Missing Group:5.39<br> Mean  Difference: -5362.5<br><br> Column &#39;OtherPay&#39;:<br> Mean  in Missing Group:4,408.79<br> Mean in Non Missing Group:4,408.79<br> Mean  Difference: 598.3<br><br> Column &#39;Benefits&#39;:<br> Mean  in Missing Group:5,321.33<br> Mean in Non Missing Group:5,321.33<br> Mean  Difference: -18810.4<br><br> Column &#39;TotalPay&#39;:<br> Mean  in Missing Group:4,414.18<br> Mean in Non Missing Group:4,414.18<br> Mean  Difference: -74394.1<br><br> Column &#39;TotalPayBenefits&#39;:<br> Mean  in Missing Group:9,735.50<br> Mean in Non Missing Group:9,735.50<br> Mean  Difference: -93204.5<br><br><br></pre><p>By analyzing the results, we found that there are 10 unique job titles that appear only when BasePay is missing. There is also an income gap between the two subsets, which indicates that the missing BasePay is Missing At Random (MAR), as it is tied to specific incomes and job titles.</p><p><strong>Second: verify the validity of statement (When BasePay has NaN value the OvertimePay is equal to zero and TotalPay is equal to OtherPay) , we will test it mathematically using the np.isclose method:</strong></p><pre>def impute_BasePay(cols):<br>    BasePay = cols[0]<br>    TotalPay = cols[1]<br>    OtherPay = cols[2]<br>    OvertimePay= cols[3]<br>    if pd.isnull(BasePay):<br>       if np.isclose(OtherPay,TotalPay) and  np.isclose(OvertimePay,0.0) :<br>            return 0.0<br>       elif  np.isclose(TotalPay, OtherPay + OvertimePay):<br>        return 0.0<br><br>    else:<br>        return TotalPay - (OtherPay + OvertimePay)<br>df[&#39;BasePay&#39;] = df[[&#39;BasePay&#39;,&#39;TotalPay&#39;,&#39;OtherPay&#39;,&#39;OvertimePay&#39;]].apply(impute_BasePay,axis=1)<br>df[&#39;BasePay&#39;].isnull().sum()</pre><p><strong>Output:</strong></p><pre>np.int64(0)</pre><h4>Summary:</h4><p><strong>In this story, we study missing values. We start by cleaning the data to check for null values and try to find the reason for their absence by analyzing the relationship between missing values and other features. Then, we decide the missing type based on the results</strong></p><p><strong>I hope this story brought you some value. Hit the follow button to stay updated on my next articles, and feel free to share your thoughts.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2fb6ce019af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning In Production , MLOps & Machine Learning Lifecycle Part2: Scoping]]></title>
            <link>https://medium.com/@engulayousef99/machine-learning-in-production-mlops-machine-learning-lifecycle-part2-scoping-5c80d8719487?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c80d8719487</guid>
            <category><![CDATA[feasibility]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[project-scoping]]></category>
            <category><![CDATA[human-level-performance]]></category>
            <category><![CDATA[business-metrics]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 20:47:06 GMT</pubDate>
            <atom:updated>2026-07-20T20:47:06.433Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don’t build your system on sand, why ML scoping is the most important step</h4><h4>This story is the second part of the series :<a href="https://medium.com/@engulayousef99/machine-learning-in-production-mlops-machine-learning-lifecycle-part1-0d73e146325d?sharedUserId=engulayousef99">machine-learning-in-production-mlops-machine-learning-lifecycle-part1</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*c032UPyJpxmqsVsd.png" /><figcaption>image made by me (inspired by prof Andrew Ng’s course)</figcaption></figure><blockquote><strong>“You will spend 80% of your time on data preprocessing”. Yes, this is the first and most common sentence both of you and me have heard when starting to learn AI and data science. We also hear things like, “The more time you spend on data preprocessing, the better your AI system will perform.”</strong></blockquote><p>Are those sentences true? Yes, they are.</p><p>Should they be our top priority? No.”</p><p>Because spending 80% of your time at data preprocessing without studying system feasibility is a waste of resources, what is the purpose of spending 80% or more at data processing for a project that doesn’t make sense in the real world. This is exactly why project scoping is essential.</p><h3>What is scoping:</h3><p>According to the Machine Learning in Production course from DeepLearning.AI, scoping means picking the right project to work on and planning out the scope of the project. It involves going through several key phases.</p><p>To help you understand this well, I will provide an analogy: let’s say a ML system is a house you want to build. So what are the most important things to focus on before you start building?</p><ol><li><strong>Check Land and Soil Quality</strong>: Evaluating soil quality before building a house is a crucial step to ensure the long-term safety and stability of your home, as not all soils are equally fit to build upon. We take this exact same approach in the first step of building an AI project: we check if AI is a suitable solution for our specific problem. After all, not every problem can be solved with AI.</li><li><strong>Defining ideas about the design of a house: </strong>This is the same as translating the AI solution you find into an ML task. Let’s say we want to build an AI system that analyzes a customer’s past purchases and browsing behavior to predict and display hyper-personalized product recommendations in real-time, thereby increasing both user engagement and average order value.</li><li><strong>Assess feasibility and value of potential design</strong>: Evaluating whether the chosen house design can be executed within defined constraints — such as time, budget, resources, and legal permits — before construction begins.</li><li><strong>Determine Success Metrics:</strong> Define the success criteria. The house must be built up to modern building codes, pass all electrical and plumbing inspections, and be completed by a specific date. This is the exact same approach we take while scoping ML projects: we define both business metrics (e.g., response, latency) and ML metrics (e.g., 95% accuracy or a specific F1-score).</li><li><strong>Budget for resources:</strong> Secure the construction loan, hire general contractors and architects, and schedule material deliveries (lumber, concrete, appliances); similarly, for an ML project, we must calculate the required budget, including computing power, cloud infrastructure, domain experts, data labeling costs, and project timelines.</li></ol><h4>Keep in mind: <strong><em>A house is only as strong as its foundation. You can’t build a strong ML system on a weak foundation.</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*uDLvt8v71yLyRCQjDp2KPQ.png" /><figcaption>image made by me (inspired by prof Andrew Ng’s course)</figcaption></figure><h3><strong>How to assess the feasibility and value of potential solutions?</strong></h3><p><strong><em>Feasibility:</em></strong><em> i</em>s about determining whether a project can be completed. Sometimes, you must use external benchmarks (e.g., industry literature, organizational publications, or company reports) to check if anyone has successfully managed the task before.</p><p><strong><em>Value</em></strong>: Is the project worth building?</p><p>Assessing project feasibility depends on the type of data, and whether the system is being developed for the first time or if an existing one is being modified. The figure below outlines how to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*e0fvOe2VRcmPf8vUYl8WuQ.png" /><figcaption>image made by me (inspired by prof Andrew Ng’s course)</figcaption></figure><h4>But what is HLP?</h4><p>HLP (Human-Level Performance) is a way to establish a baseline, which we use during scoping. This is especially true for unstructured data (audio, images, and video) that humans are good at understanding and interpreting. It helps us with:</p><ol><li><strong>Setting a performance threshold:</strong> by determining the highest achievable accuracy, we can establish a baseline. For example, if the HLP can achieve 90% accuracy on a task while our model only achieves 60%, this serves as a flag indicating we must improve the model’s performance.</li><li><strong>Guiding error analysis:</strong> If our model fails to reach the HLP, we will shift our focus from model performance to other issues, such as poor data quality or the need for data augmentation.</li><li><strong>Prove that the ML system is superior to humans doing the job.</strong></li><li><strong>Resolving labeling ambiguity:</strong> By comparing the performance of multiple human annotators, HLP helps identify inconsistent labels and clarify ambiguities in the training dataset.</li></ol><p><strong>Some considerations to keep in mind when assessing the value and feasibility of projects:</strong></p><p><strong>Ethical consideration:</strong> even if a project is technically and financially feasible, we should determine whether it is legal and does not violate laws and ethical standards.</p><p><strong>Technical consideration:</strong> Do we have the required technology, infrastructure, and technical skills to carry out the task?</p><h3><strong>How to determine milestones (and define success metrics?)</strong></h3><p><strong>Legend has it that there is a constant conflict between the Machine Learning team and the business team</strong>. Because the ML team focuses entirely on technical metrics — such as precision, accuracy, and the F1 score — the business team focuses strictly on business metrics, like revenue, profit, and customer lifetime value. To bridge this gap, the two teams should collaborate to set technical and business metrics that they both agree on.</p><p>Another important metrics is <strong>visibility </strong>(stakeholder alignment): is about ensure that teams, sponsors and users agree on the final outcome of the project, it also means build a system that people trust it and know how to use it.</p><p>Another important metric is <strong>visibility </strong>(stakeholder alignment): it is about ensuring that teams, sponsors, and users agree on the final outcome of the project. It also means building a system that people trust and know how to use.</p><p>Your role as a Machine Learning engineer is to find the technical metrics that align well with business goals and objectives. So, instead of saying, “We want to build an E-Commerce recommendation system that achieves specific accuracy”, think, “We need to increase the total sales of certain items on an E-commerce platform”. Therefore, we will optimize the model for precision on high-margin items rather than just overall accuracy.</p><p><strong>Keep in mind: “<em>AI usage is a tool, not a goal. As ML and AI engineers, our primary job is solving business problems that require AI while striking a balance between model success metrics and business success metrics. Therefore, our objective is not just achieving high accuracy or precision, but ensuring that those metrics drive the final business goals.</em></strong><em>”</em></p><h3>key specifications of resources:</h3><p><strong>Personnel required include:</strong></p><ul><li><strong>Labelers:</strong> for raw data annotation.</li><li><strong>Machine learning engineers and data scientists:</strong> to build and fine-tune models.”</li></ul><p><strong>Data Acquisition: </strong>Costs for gathering, labeling, and storing data.</p><p><strong>Timeline:</strong> setting a deadlines to schedule every project phase from data gathering to final product release.</p><p>key timelines tracked:</p><ul><li>Data gathering periods.</li><li>Model training starts.</li><li>Deployment dates.</li><li>First version release.</li></ul><p><strong>Computer resources include the costs of the CPU, GPU, and memory.</strong></p><h3>Summary:</h3><p>In this story we emphasized the importance of scoping as a way to study the foundation of your project before you start building it.</p><p>We discussed the steps of the scoping process, which include defining the business problem and brainstorming an AI solution that fits ethical and technical considerations without violating laws. Finally, we covered the key ideas for determining success metrics and milestones.</p><p>I will keep writing about MLOps, so stay tuned and enjoy reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c80d8719487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning In Production , MLOps & Machine Learning Lifecycle Part1]]></title>
            <link>https://medium.com/@engulayousef99/machine-learning-in-production-mlops-machine-learning-lifecycle-part1-0d73e146325d?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d73e146325d</guid>
            <category><![CDATA[data-drift]]></category>
            <category><![CDATA[data-centric-ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[concept-drift]]></category>
            <category><![CDATA[model-centric-ai]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 12:32:58 GMT</pubDate>
            <atom:updated>2026-06-21T12:52:51.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>The greatest trick the Devil ever pulled was convincing the world that a machine learning project lifecycle ends when achieving high accuracy. And like that… he’s gone.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*HL-aiN-Y7jKkeKs0vOX7Yw.png" /><figcaption>image made by me (inspired by Andrew Ng’s course)</figcaption></figure><p>I am sorry if the title makes you feel wired, but yes this is the truth; achieving high accuracy after a period of training ml model is not the end, it is a new beginning for another challenges you have to go through. If you want a solid evidence to keep reading this article just return back to the previous image and focus on the word cycle in the ML Project Lifecycle.</p><h4>Why ML Lifecycle and MLOps:</h4><p>Suppose there are two data science enthusiasts who are working on a machine learning classification project. The first one finishes his/her task with 0.92% accuracy, the second finishes his/her task with 0.66% accuracy. I know your gut feeling will tell you that the first one has passed and the other has failed, but believe me, both of them are in trouble if they stop there. Achieving 0.92 % or 0.66% in a notebook means very little if the model cannot be deployed and monitored, what is the purpose of high accuracy if no one can use your project to achieve a real task, or your model didn’t see the light of the day.</p><p><strong><em>Keep in mind: an ML model in Jupyter notebook is just a hypothesis, while an ML model in production is a product</em></strong></p><h4>What is the difference between ML Lifecycle and MLOps (Machine Learning Operations):</h4><p><strong>ML Lifecycle</strong>: is an iterative process of designing, building, deploying and maintenance model, aiming to make sure that the model works well in production environment, it goes through four steps:</p><ol><li>Scoping : Define project and the problem you want to solve (classification, regression, clustering…).</li><li>Data: determine the data that required to solve the problem, establish a baseline for it, with focus on labeling and organizing it.</li><li>Modeling: select the model that serves to achieve the project, and perform error analysis.</li><li>Deployment: deploy model in production, then monitor and maintain system.</li></ol><p><strong>MLOps (Machine Learning Operations):</strong> is a discipline comprising a set of tools and principles that govern the ML lifecycle. Essentially, it is a set of practices used to take machine learning models into production</p><h4>Key questions you should ask yourself and team members before starting any ML project:</h4><p>To make sure you will find the desired answers, you should ask the right questions, Let’s try to use 5W rule to do that:</p><h4><strong>Who:</strong></h4><p>who will use the project: determine end users, stakeholders, business unit.</p><h4>What:</h4><ol><li>What is the problem we want to solve, example: ECG Based Heart Disease Diagnosis</li><li>What is the tool we want to use, what is the resources we have</li><li>What is the philosophy we want to use , here we have to recognize between two types :</li></ol><p><strong><em>Model centric view</em> </strong>: used in academic research when we take the data and try to develop a model that does as well as possible on it, that is why we called model centric because we focus on development a model on a fixed data, hold the data fixed and iteratively improve the code &amp; model.</p><p><strong><em>Data centric view </em></strong>: which we use in real-world applications, here we improve the data aiming to make multiple model able to do well on it, so the model is fixed and we try to improve data iteratively.</p><p>Our question should be like that: am I trying to build a system, app for heart diseases diagnose with Electrocardiogram (ECG) data or I want to develop a model that work well on time series data.</p><h4>Where:</h4><p>Where will the data come from, and where will the model live : will we use a data from open sources like Kaggle, World Bank Open Data, Data.gov or we will collect the data , then where will the model deploy: in cloud (Server-side) or browser (Client-side), or at edge.</p><h4>Why:</h4><p>Why do we want to build this app or system if another one already does the same task? for example do we want to increase accuracy by 30% compared to the other one, or reduce costs by 20%? If our model performs the same task while consuming the exact same resources, time, and effort without making any improvements, so what is the purpose of developing it?</p><h4>When:</h4><p>Establishing a deadline for each phase of MLOps can help us determine when we will start and finish gathering data, when we will begin training the model, when we will deploy it, when we will conduct error analysis, and when we will release the first version of the product.</p><h4>Important things to consider while working on ML system:</h4><ol><li>Developing an ML system is not a sequential process, so you will find yourself iterating through the same phases multiple times. For example, you may return to data preparation after model evaluation fails.</li><li>Not all systems are worth building, and not all problems can be solved with AI.</li><li>Sometimes you cannot know what mistakes you made during a specific phase until you reach the final step. For example, you will not notice if your data was processed incorrectly until the model behaves poorly in production.</li><li>An active model does not mean a long-lived model: even if your model is running in production, it can die due to environmental changes. There are two types of changes that can lead to a drop in your model’s performance:</li></ol><p><strong><em>Data Drift: </em></strong>This occurs when the statistical distribution of data changes over time, meaning your model will encounter surprises in the production phase because the incoming data differs from the data it was trained on. For example, imagine you build a system for online shopping predictions. Your model is trained on features of summer clothes (e.g., bright colors, lightweight fabrics). When the production phase arrives, winter begins, and user inputs shift to heavy jackets and boots → The model is forced to make predictions on unfamiliar data → the model fail.</p><p><strong><em>Concept Drift: </em></strong>This occurs when the statistical relationship between input variables x and the target variable y shifts over time. For example while I was working on predicting Syrian commodity prices. The prices of items rose exponentially because the underlying drivers of the Syrian market during the war — like extreme inflation, economic sanctions, changing agricultural policies, and supply chain bottlenecks, led to historical data patterns frequently broke down.</p><h4>Summary:</h4><p>This article is a simple introduction to MLOps, aiming to pave the way for those who want to understand the phases of an ML project from scoping, data, and modeling to deployment, while focusing on the key considerations you must pay attention to before starting to build any ML system.</p><p>This article is the first in my new MLOps tutorial series. I will keep writing about MLOps, so stay tuned. Enjoy reading, and don’t hesitate to share your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d73e146325d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Introduction To OOP (Object Oriented Programming)]]></title>
            <link>https://medium.com/@engulayousef99/a-simple-introduction-to-oop-object-oriented-programming-b8abd2e06df4?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8abd2e06df4</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[abstraction]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Wed, 20 May 2026 23:28:28 GMT</pubDate>
            <atom:updated>2026-05-20T23:34:07.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*PrrbvOew1smfXh4ciBaOkg.png" /><figcaption>image from Pixabay</figcaption></figure><p>I still remember the first time I tried to learn programming, my code was absolutely riddled with mistakes<em>, </em>and my attempts to fix the errors were like opening a can of worms. This learning journey reminds me of my first time shopping at the store near my house, — it was terrible experience for many reasons….</p><p>First of all: there is no specific section for each product for example there is no certain part for frozen food, meat and seafood, or household goods. Therefore if you are looking for any item (let’s say coffee) you are supposed to look around all the counters.</p><p>Second: there were no price tags next to the items, so I had to read a long list to find the price of what I wanted to buy.”</p><p>Third: some items in the list that — which I read to know the price — are too sensitive to be written down, for example while I was looking for the coffee’s price, I found a line with info about the total revenue of coffee over the past three months, not only this but when I flipped the list over I found a lot of lines detailing the salary of some workers (salesperson, cashier, sales associate).</p><p>Fourth: The list was written in a chaotic style. For instance, it stated there was a 20% discount on coffee. However, at checkout, the cashier informed me this offer only applied to espresso, rather than the cappuccino I had chosen.</p><p>Fifth: the price calculation formula has been repeated in the list next to every single item, even though some of them share the same tax, such as food or luxury. Writing prices in this way is a waste of time. If the tax law changes, we would have to manually rewrite the formula for thousands of items!</p><p>The price list with the repeated formulas looks like this:</p><pre>Milk: price + (price * 0.05) (5% Food Tax)<br>Bread : price +(price * 0.05) (5% Food Tax)<br>Shampoo: price + (price * 0.18) (18% Luxury Tax)<br>Perfume : price + (price * 0.18) (18% Luxury Tax)<br>Soup : price +(price * 0.18) (18% Luxury Tax)</pre><p>Sixth: the payment method was complicated. You couldn’t just go to the checkout and pay for products; instead, you were supposed to wait in a line based on your type of payment. There were many lines: one for cash, one for credit card, and another for digital wallet/phone. This process frustrated customers who had only one type of payment and were stuck in the wrong line. It also led to operational inflexibility; for example, if the cashier had an empty card terminal but could not assist a long line of cash-paying customers, it resulted in inefficient staffing.</p><h3><strong>If you ask me if this story is true or if this place really exists, I would say I doubt it, but I am sure that you will experience the same chaos if you write code without following OOP principles</strong></h3><h3>What is OOP:</h3><p>OOP is a programming paradigm that provide a clear structure to programs, making the code easier to maintain and more organization, it also help at build application with less code.</p><p>The core of OOP is class and object. class is the template or blueprint you set to define the attributes and method you need, where as object is the filled template of this class which hold a real values of data and methods.</p><p>Classes can help us with data organization by grouping related variables (attributes) and functions (methods) together. This approach offers a perfect solution to the first and second problem :</p><p>First problem: — the lack of specific sections for each product — by allowing us to categorize items and customize each product, such as creating specific parts for frozen food or household items.</p><p>Second problem: — no price tags beside the items — by structuring products into classes (e.g., Coffee) containing specific attributes: name, price, category, id, and barcode.</p><h3>The Key of OOP:</h3><h4>Inheritance:</h4><p>a mechanism that save your time and enable you to write less code by apply the DRY principle (Don’t Repeat Yourself), therefore instead of write the same code multiple times , you can just define a class<strong> (parent class ) </strong>as a container of all the methods and attributes then let the other classes (<strong>child classes</strong>) to inherit what they need from it.</p><p>Returning to the market example, we can use inheritance to solve the fifth problem (create tax categories) by creating a parent class called Product. then we create child classes for each specific tax rules. The formula is written exactly once in the parent class, and the child classes just provide their specific tax rate.</p><pre>class Product: # 1. The Parent Class holds the universal calculating formula<br>  def __init__(self, name, base_price):<br>    self.name = name<br>    self.base_price = base_price<br>    self.tax_rate = 0.00 # Default tax is 0% # This is the single method passed to all items<br>  def calculate_final_price(self):<br>    return self.base_price + (self.base_price * self.tax_rate)<br>class Food(Product):#Child Class Food: inherits the formula, but sets tax to 5%<br>  def __init__(self, name, base_price):<br>    super().__init__(name, base_price)<br>    self.tax_rate = 0.05<br>class Luxury(Product): # Child Class Luxury: inherits the formula, but sets tax to 18%<br>  def __init__(self, name, base_price):<br>    super().__init__(name, base_price)<br>    self.tax_rate = 0.18<br>class Beverages(Product): # Child Class Beverages: inherits the formula, but sets tax to 3%<br>  def __init__(self, name, base_price):<br>    super().__init__(name, base_price)<br>    self.tax_rate = 0.03</pre><pre>if __name__ == &quot;__main__&quot;:<br>  item1=Food(&#39;Meat&#39;,8.00)<br>  item2=Food(&#39;Fresh Bread&#39;,2.00)<br>  item3=Luxury(&#39;Designer Perfume&#39;,80.00)<br>  item4=Beverages(&#39;Coffee&#39;,10.00)<br>  print(f&quot;{item1.name} Final Price:${item1.calculate_final_price():.2f}&quot;)<br>  print(f&quot;{item2.name} Final Price:${item2.calculate_final_price():.2f}&quot;)<br>  print(f&quot;{item3.name} Final Price:${item3.calculate_final_price():.2f}&quot;)<br>  print(f&quot;{item4.name} Final price ${item4.calculate_final_price():.2f}&quot;)</pre><p>Output:</p><pre>Meat Final Price:$8.40<br>Fresh Bread Final Price:$2.10<br>Designer Perfume Final Price:$94.40<br>Coffee Final price $10.30</pre><h4>Abstraction:</h4><p>The concept of hiding complex implementation details while exposing only the essential features of an object. we focus on what an object does rather than how it does it. There are two main tools to achieve abstraction:</p><ol><li><strong>Abstract Classes</strong>: classes that cannot be instantiated directly. They act as a template, defining a common set of methods that derived subclasses must implement, while occasionally providing some concrete, reusable code</li><li><strong>Interfaces</strong>: A strict contract containing only method signatures with no implementation details. Any class that implements an interface must provide the specific code for every method</li></ol><h4>Polymorphism (many forms):</h4><p>It is the ability of a single interface or name to represent different forms of behavior, there are two main ways to apply that:</p><ol><li><strong>Runtime Polymorphism (Method Overriding):</strong> this occurs when a subclass provides its own implementation of a method already defined in its parent class. We define a general method in the parent class; when subclasses inherit it, each one of them overrides the method to perform its own specific task.</li><li><strong>Compile-Time Polymorphism (Method Overloading):</strong> this occurs when multiple methods in the same class have the same name but different signatures (different number or types of parameters), we create several versions of a method within one class, with ensuring that each version accepts different arguments.</li></ol><p>To capture the real example of this let’s come back to the market visit (sixth problem), instead of have multiple lines for payment process we can have one accepts all payment types like :cash, credit cards, and digital wallets/phone payments</p><p>Payment class( parent class) that defines the process payment and then define the following class :</p><p>CashPayment (Subclass): Implements process payment by handling cash tender and change.</p><p>CreditCardPayment (Subclass): Implements process payment by validating card details and processing through a gateway.</p><p>DigitalWalletPayment (Subclass): Implements process payment via phone app integration or QR code.</p><pre>from abc import ABC, abstractmethod<br><br>class Payment(ABC): # abstract class for Payment<br>    @abstractmethod<br>    def process_payment(self, amount: float):<br>        pass<br><br>class CashPayment(Payment):<br>    def __init__(self, cash_tendered: float):<br>        self.cash_tendered = cash_tendered<br><br>    def process_payment(self, amount: float):<br>        if self.cash_tendered &lt; amount:<br>            return f&quot;Error: Insufficient cash. Need ${amount}.&quot;<br>        <br>        change = self.cash_tendered - amount<br>        print( f&quot;Processed cash payment of ${amount}. Change returned: ${change:.2f}.&quot;)<br><br>class CreditCardPayment(Payment):<br>    def __init__(self, card_number: str, expiry_date: str, card_verification_value: str):<br>        self.card_number = card_number<br>        self.expiry_date = expiry_date<br>        self.card_verification_value = card_verification_value<br><br>    def validate_card(self):<br>        return len(self.card_number) == 16 and len(self.card_verification_value) == 3<br><br>    def process_payment(self, amount: float):<br>        if self.validate_card():<br>            print(f&quot;Processing Credit Card Payment of ${amount:.2f}&quot;)<br>        else:<br>            print(&quot;Card validation failed.&quot;)<br><br>class DigitalWalletPayment(Payment):<br>    def __init__(self, wallet_id: str):<br>        self.wallet_id = wallet_id<br><br>    def process_payment(self, amount: float):<br>        print(f&quot;Initiating QR code for Wallet ID: {self.wallet_id}...&quot;)<br>        print(f&quot;Processing digital wallet payment of ${amount:,.2f}.&quot;)<br></pre><pre>if __name__ == &quot;__main__&quot;:<br>    # 1. Cash Payment<br>    cash = CashPayment(160.00)<br>    cash.process_payment(90.00)<br><br>    # 2. Credit Card Payment<br>    card = CreditCardPayment(&quot;1234567812345678&quot;, &quot;12/28&quot;, &quot;123&quot;)<br>    card.process_payment(150.00)<br><br>    # 3. Digital Wallet Payment<br>    wallet = DigitalWalletPayment( &quot;user_phone_123&quot;)<br>    wallet.process_payment(320.00)</pre><p>Output:</p><pre>Processed cash payment of $90.0. Change returned: $70.00.<br>Processing Credit Card Payment of $150.00<br>Initiating QR code for Wallet ID: user_phone_123...<br>Processing digital wallet payment of $320.00.</pre><p>Also we can fix fourth issue: ( the 20% discount on coffee, which applies only on espresso, not cappuccino) by creating a Parent class called Coffee that inherit from Beverages with apply_discount() method, and subclasses (Espresso ,Cappuccino ) that inherit from Coffee class.</p><ul><li>Overriding (Espresso): Overrides apply_discount() to set a 20% discount.</li><li>Overriding (Cappuccino): Overrides apply_discount() to set a 0% discount.</li></ul><pre>class Coffee(Beverages):<br>  def __init__(self,name,base_price):<br>    super().__init__(name,base_price)<br>    self.tax_rate = 0.03<br>  def apply_discount(self):<br>    return self.calculate_final_price()<br>class Espresso(Coffee):<br>  def apply_discount(self):<br>    return self.calculate_final_price() * 0.80 # Overrides to apply a 20% discount<br><br>class Cappuccino (Coffee) :<br>  def apply_discount(self):<br>    return self.calculate_final_price()  # Overrides to apply a 0% discount.<br>if __name__ == &quot;__main__&quot;:<br>  espresso= Espresso(&quot;Espresso&quot;,50.00)<br>  cappuccino=Cappuccino(&quot;Cappuccino&quot;,30.00)<br>  print(f&quot;{espresso.name} price:${espresso.apply_discount():.2f}&quot;)<br>  print(f&quot;{cappuccino.name} price: ${cappuccino.apply_discount():.2f}&quot;)</pre><p>Output:</p><pre>Espresso price:$41.20<br>Cappuccino price: $30.90</pre><h4>Encapsulation:</h4><p>protecting data inside the class by bundling attributes and methods, while controlling how the data is accessed from outside the class.</p><p>Python achieves encapsulation through access modifiers, which are naming conventions that indicate how a member should be accessed. There are 3 types of encapsulation in python:</p><ol><li>Public: attributes or methods that can be access anywhere, there is no underscore prefix to it</li><li>Protected: attributes or methods that can be access inside the class and its child classes, denoted by one underscore prefix</li><li>Private: attributes or methods that can be access only inside the class, denoted by double underscore prefix</li></ol><p>Encapsulation can be a perfect solution to the third problem by hiding sensitive data: as I am only supposed to see the coffee price, the class only exposes necessary information, keeping sensitive data (revenue) private. Let’s make revenue private by a writing a double underscore __ prefix:</p><pre>class Coffee(Beverages):<br>  def __init__(self, name, base_price, revenue):<br>    super().__init__(name,base_price)<br>    self.tax_rate = 0.03<br>    self.__revenue = revenue # Private (Encapsulated)        <br><br>  def apply_discount(self):<br>    return self.calculate_final_price()<br><br>class Espresso(Coffee):<br>  def apply_discount(self):<br>    return self.calculate_final_price * 0.80 <br><br>class Cappuccino(Coffee):<br>  def apply_discount(self):<br>    return self.calculate_final_price()  <br>if __name__==&quot;__main__&quot;:<br>  espresso = Espresso(&quot;Espresso&quot;, 50.00, 950)<br>  cappuccino = Cappuccino(&quot;Cappuccino&quot;, 30.00, 700)<br>  print(f&quot;{espresso.name} revenue: ${espresso.__revenue:.2f}&quot;)<br>  print(f&quot;{cappuccino.name} revenue price: ${cappuccino.__revenue:.2f}&quot;)</pre><p>Output :</p><pre>AttributeError: &#39;Espresso&#39; object has no attribute &#39;__revenue&#39;</pre><p>An AttributeError is Raised when we tried to access private attribute (revenue).</p><p>If we want to access revenue, we can use a getter method, which only enables you to read private data, not modify it.</p><pre>class Coffee(Beverages):<br>   def __init__(self, name, base_price, revenue):<br>    super().__init__(name,base_price)<br>    self.tax_rate = 0.03<br>    self.__revenue = revenue  # Private (Encapsulated)   <br> <br>   def apply_discount(self):<br>    return self.calculate_final_price()<br><br>  # Getter method to access the private _revenue attribute<br>   def get_revenue(self):<br>    return self.__revenue<br><br>class Espresso(Coffee):<br>  def apply_discount(self):<br>    return self.calculate_final_price() * 0.80 <br><br>class Cappuccino(Coffee):<br>  def apply_discount(self):<br>    return self.calculate_final_price()  <br>if __name__==&quot;__main__&quot;:<br>  espresso = Espresso(&quot;Espresso&quot;, 50.00, 10000)<br>  cappuccino = Cappuccino(&quot;Cappuccino&quot;, 30.00, 7500)<br>  print(f&quot;{espresso.name} Final_price: {espresso.apply_discount()} revenue: {espresso.get_revenue()}&quot;)<br>  print(f&quot;{cappuccino.name} Final_price: {cappuccino.apply_discount()} revenue: {cappuccino.get_revenue()}&quot;)</pre><p>Output:</p><pre>Espresso Final_price: 41.2 revenue: 10000<br>Cappuccino Final_price: 30.9 revenue: 7500</pre><p>In this story, we highlighted the importance of OOP by breaking down its core principles: abstraction, inheritance, polymorphism, and encapsulation with real-world examples. We started by gathering related attributes and methods into one class. Then, we let other classes inherit common features from their parent to avoid repeating the same code. Next, we applied polymorphism by allowing the same method from a parent class to behave differently based on the child class’s logic. Finally, we showed how to keep data protected using encapsulation.</p><p>I hope this story serves as a useful guide for learners. If you need further information, please don’t hesitate to ask. Any feedback will be welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8abd2e06df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction To Statistics: Speak The Language Your Data Is Talking]]></title>
            <link>https://medium.com/@engulayousef99/a-gentle-introduction-to-statistics-speak-the-language-your-data-is-talking-6f1c1e4db710?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f1c1e4db710</guid>
            <category><![CDATA[modality]]></category>
            <category><![CDATA[variability]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[skewness]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 15:09:07 GMT</pubDate>
            <atom:updated>2026-02-23T19:06:50.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Stephen R. Covey said : <strong>The key is in not spending time, but in investing it.</strong><br> I say: <strong>The key is not learning data science, but investing in learning statistics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*VB1x-hjRWBEQX2FM.jpg" /></figure><p>I have seen many people on their early career professional wonder how to become data scientist or data analyst, many of them hope to pursue a career in any data field, the critical difference between those who move foreword on their learning journey and those who didn’t is <strong>statistic, </strong>statistic is the golden ticket to travel the world of data.</p><h4><strong>what is statistics :</strong></h4><p><strong>Statistics</strong>: is the science of collection, organization, analysis, interpretation, and presentation of data to recognize pattern and make decision.</p><p>There are two types of statistics:</p><p>1- <strong>Descriptive statistics:</strong> which summarize data to describe the main features like Measure of Central Tendency (Mean, Median, Mode), Measure of Variability (Range, Variance, Standard Deviation).</p><p>2- I<strong>nferential statistics: </strong>which use a sample to make generalization or predictions about a larger population using tools like Hypothesis Testing and confidence intervals.</p><p>Let’s move to practical section</p><p>In This story we will use Pima-Indians-Diabetes-Dataset.</p><h4>Import libraries:</h4><pre>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>from scipy import stats<br>from statsmodels.stats.proportion import proportions_ztest</pre><h4><strong>Reading the data set:</strong></h4><pre>df=pd.read_csv(&#39;/content/diabetes.csv&#39;)<br>df</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*W3VRdsp7PuibI_ITqRC64g.png" /></figure><h4><strong>Check null values:</strong></h4><pre>df.isnull().sum()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*pNCwT-rayIPaSVgv4koD7w.png" /></figure><h4><strong>Check duplicated values:</strong></h4><pre>df.duplicated()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*DpqNAGDnf_IWkpgxqV5rDw.png" /></figure><h4><strong>Outlier detection:</strong></h4><pre>sns.set(style=&quot;ticks&quot;)<br>f, axes = plt.subplots(4, 2, sharey=False, figsize=(8, 8))<br>sns.boxplot(y=df[&quot;Pregnancies&quot;],ax = axes[0,0], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;Glucose&quot;],ax=axes[0,1], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;BloodPressure&quot;],ax=axes[1,0], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;SkinThickness&quot;],ax=axes[1,1], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;Insulin&quot;],ax=axes[2,0], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;BMI&quot;],ax=axes[2,1], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;DiabetesPedigreeFunction&quot;],ax=axes[3,0], color=&#39;purple&#39;)<br>sns.boxplot(y=df[&quot;Age&quot;],ax=axes[3,1], color=&#39;purple&#39;)<br>plt.tight_layout()<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*ke2ol7s1Or4pWXibV0jSAA.png" /></figure><h4><strong>Remove outliers using flooring capping technique:</strong></h4><pre>def flooring_capping(df,columns):<br>  for col in columns:<br>    if col in df.columns:# check if the columns are in dataframe, maybe we pass a wrong name of column<br>        lower_bound = df[col].quantile(0.10)# check the lower_percentile of column<br>        upper_bound = df[col].quantile(0.90)# check the upper_percentile of column<br>        df[col] = df[col].clip(lower=lower_bound, upper=upper_bound)# clip method to replace value less than the specified minimum  with the minimum value, and value  greater than the specified maximum, with the maximum value<br>  return df</pre><pre>columns=[&#39;Pregnancies&#39;,&#39;Glucose&#39;,&#39;BloodPressure&#39;,&#39;SkinThickness&#39;,&#39;Insulin&#39;,&#39;BMI&#39;,&#39;DiabetesPedigreeFunction&#39;,&#39;Age&#39;]<br>df=flooring_capping(df,columns)</pre><p>Check the columns after removing outliers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*5DN5_uRlCTC336DMJPeGUA.png" /></figure><p><strong>Handling zeros which mean missing values in some features:</strong></p><p>we have several medical features with zero which is a placeholder for a missing value and will lead to inaccurate analysis, for example:</p><p>Skin Thickness<strong>:</strong> A value of zero for skin fold thickness is biologically impossible.</p><p>Insulin<strong>:</strong> even though the body can produce a low levels of insulin, a recorded value of zero is often an indication of missing data.</p><p>we will handle the zeros by replacing them with mean value for ach column:</p><pre>df[&#39;SkinThickness&#39;]= np.where(df[&#39;SkinThickness&#39;] == 0, df[&#39;SkinThickness&#39;].mean(), df[&#39;SkinThickness&#39;])<br>df[&#39;Insulin&#39;]= np.where(df[&#39;Insulin&#39;] == 0, df[&#39;Insulin&#39;].mean(), df[&#39;Insulin&#39;])</pre><p>Create a new column from the target variable as categorical:</p><pre># Define the mapping<br>mapping = {0: &#39;non_diabtes&#39;, 1: &#39;diabtes&#39;}<br>df[&#39;Outcome1&#39;] = df[&#39;Outcome&#39;].map(mapping)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*Rdp0bUMH4TXj7NYVY0v6Yg.png" /></figure><h4><strong>Drop Outcome column from data frame:</strong></h4><pre>df.drop(columns=&#39;Outcome&#39;,inplace=True)</pre><h3>Descriptive Statistics: <strong>Measure of Central Tendency:</strong></h3><p>Mean: the average value of all elements in the data.</p><p>Median: the mid point in sorted elements of data</p><p>Mode: the most repeated value.</p><h4><strong>Calculate the mean ,median and mode of numerical data:</strong></h4><p>First we select the numerical features:</p><pre>df_numerical= df.select_dtypes(include=&#39;number&#39;)<br>df_numerical.dtypes</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*vIx9i2k9-Qp83vUgj4G2tA.png" /></figure><pre>def measures_of_central_tendency(data):<br>  for i in data.columns:<br>    print(&#39;the mean of {i} is {j},the median is {k} and the mode is {l}+\n&#39;.format(i=i,j=data[i].mean(),k=data[i].median(),l=data[i].mode()))</pre><pre>measures_of_central_tendency(df_numerical)</pre><p>output:</p><pre>the mean of Pregnancies is 3.6666666666666665,the median is 3.0 and the mode is 0    1<br>Name: Pregnancies, dtype: int64+<br><br>the mean of Glucose is 120.69010416666667,the median is 117.0 and the mode is 0     85<br>1    167<br>Name: Glucose, dtype: int64+<br><br>the mean of BloodPressure is 71.28645833333333,the median is 72.0 and the mode is 0    54<br>Name: BloodPressure, dtype: int64+<br><br>the mean of SkinThickness is 25.845667521158855,the median is 23.0 and the mode is 0    19.949219<br>Name: SkinThickness, dtype: float64+<br><br>the mean of Insulin is 98.58013576931425,the median is 66.29557291666667 and the mode is 0    66.295573<br>Name: Insulin, dtype: float64+<br><br>the mean of BMI is 32.076171875,the median is 32.0 and the mode is 0    23.6<br>Name: BMI, dtype: float64+<br><br>the mean of DiabetesPedigreeFunction is 0.44139218750000003,the median is 0.3725 and the mode is 0    0.165<br>Name: DiabetesPedigreeFunction, dtype: float64+<br><br>the mean of Age is 32.524739583333336,the median is 29.0 and the mode is 0    22<br>Name: Age, dtype: int64+</pre><p><strong>Note</strong> : mean, median and mode can help us at understand central tendency , their relative positions indicate the data’s shape (Skewness) with the following rules:</p><p>if mean = median = mode then the data shape is symmetric.</p><p>if mean &gt; median &gt; mode then the data shape is Right-Skewed (Positive).</p><p>if mode &gt; median &gt; mean then the data shape is Left-Skewed (Negative).</p><p>generally the data shape can be divide into three types:</p><p>Unimodal: when there is only one mode.</p><p>Bimodal: there are two mode indicating the presence of two distinct peaks.</p><p>Multimodal: there are more than two mode.</p><h4>But are the previous rules about comparing mean, median , and mode correct always?</h4><p>unfortunately the answer is no, why?</p><p>Because the mode sometimes can be misleading when comparing measures of central tendency. In discrete variables, repeated values may cause the mode to be unstable or unrepresentative of the overall distribution. Additionally, when a variable has multiple modes, this may indicate the presence of distinct subgroups within the data. In such cases, looking at the data as a single distribution and comparing the mean, median, and mode may lead to incorrect conclusions, because each subgroup may have its own central tendency.</p><h4>So what should we do ?</h4><p>start looking to the modality before skewness: check the number of mode before comparing any value with another.</p><ol><li>if we have only one mode → the data distribution is Unimdodal → we can compare mean with median to infer skewness with the following rules:</li></ol><p>mean &gt;median : the distribution is likely right-skewed.</p><p>mean=median: the distribution is likely symmetric .</p><p>median&gt;mean : the distribution is likely left-skewed.</p><p>and here mode can helps us to identify the peak but is not required for skewness inference.</p><p>2. if we have two mode → the data distribution is bimodal → use mode to describe the multiple peaks and possible subgroups.</p><p>3.. when outliers are present, the median is preferred because the mean is sensitive to extreme values.</p><p>Coming back to the output we found:</p><p>Pregnancies: has only one mode (we can rely on comparing the mean and median) → the mean is larger than median → the data shape is likely right-skewed (positive).</p><p>Glucose: has two mode → the distribution is bimodal, maybe indicating the presence of two distinct peaks.</p><p>BloodPressure: has one mode (we can rely on comparing the mean and median) → the mean very close to the median with just a small difference → the data shape approximately symmetric, with very slight negative skewness.</p><p>SkinThickness: has one mode (we can rely on comparing the mean and median) → the mean is larger than median → the data shape is likely right-skewed.</p><p>Insulin: has one mode (we can rely on comparing the mean and median) → the mean is larger than median → the data shape is likely right-skewed.</p><p>DiabetesPedigreeFunction: has one mode (we can rely on comparing the mean and median) → the mean is larger than median → the data shape is likely right-skewed.</p><p>Age: has one mode (we can rely on comparing the mean and median) → the mean is larger than median → the data shape is likely right-skewed.</p><p>BMI: has only one mode (we can rely on comparing the mean and median) → the mean is very closed to median with small difference→ the data shape approximately symmetric (very slight right skew).</p><h3>Descriptive Statistics: Measure of Variability:</h3><p>Variance: how far a set of number is spread out from the mean ( subtract the mean from each value in the array, squaring the result, adding up all the squares, and then dividing by the number of values in the column.</p><p>Standard deviation : measure of the spread of the data in any feature. It gives us the degree to which the data points in an column deviate from the mean.</p><p>Both standard deviation and variance measure the spread of data from the mean, but <strong>standard deviation</strong> is generally better for understanding because it is expressed in the same units as the original data</p><h4>Calculate Range, Variance and Standard_deviation:</h4><pre>def range(data):<br>  for i in data.columns:<br>    print(&#39;the min of {i} is {j},the max is {k} &#39;.format(i=i,j=data[i].min(),k=data[i].max()))</pre><p>apply the function on numerical columns:</p><pre>range(df_numerical)</pre><p>output:</p><pre>the min of Pregnancies is 0,the max is 9 <br>the min of Glucose is 85,the max is 167 <br>the min of BloodPressure is 54,the max is 88 <br>the min of SkinThickness is 7.0,the max is 40.0 <br>the min of Insulin is 14.0,the max is 210.0 <br>the min of BMI is 23.6,the max is 41.5 <br>the min of DiabetesPedigreeFunction is 0.165,the max is 0.8786000000000002 <br>the min of Age is 22,the max is 51</pre><h4>Calculate Standard_deviation and Varaince:</h4><pre>def standard_deviation_and_variance(data):<br>  for i in data.columns:<br>    print(&#39;the standard_deviation of {i} is {j},the variance is {k} &#39;.format(i=i,j=data[i].std(),k=data[i].var()))</pre><pre>standard_deviation_and_variance(df_numerical)</pre><p>output:</p><pre>the standard_deviation of Pregnancies is 2.9803062123736934,the variance is 8.88222511951323 <br>the standard_deviation of Glucose is 26.33160921394994,the variance is 693.3536437961734 <br>the standard_deviation of BloodPressure is 10.680678626136995,the variance is 114.07689591481964 <br>the standard_deviation of SkinThickness is 8.330339209287407,the variance is 69.39455134179114 <br>the standard_deviation of Insulin is 53.09623700245849,the variance is 2819.210383821242 <br>the standard_deviation of BMI is 5.754195107639548,the variance is 33.11076133678291 <br>the standard_deviation of DiabetesPedigreeFunction is 0.23717697415762617,the variance is 0.05625291707056728 <br>the standard_deviation of Age is 9.873220464015354,the variance is 97.48048233105158</pre><p><strong>To understand standard deviation we have to compare it with mean:</strong></p><ul><li>small standard deviation relative to mean → low variability.</li><li>large standard deviation relative to mean → high variability.</li></ul><p>This approach is easy in principle but hard in practice especially when you are working on data consist of a lot of features making check out the mean and median more time consuming , in addition, deciding whether the standard is small or large relative to mean is not something you can discover by soul searching, like compare 3 with 50 and just say 3 is small relative to 50, for this reason professional statisticians used <strong>Coefficient of</strong> <strong>Variation (cv)<em> </em></strong>as an established rule, that expresses the ratio of Standard Deviation to the mean then used general rules of thumb for interpretation:</p><ul><li><strong>below 10% :</strong> little variation</li><li><strong>between 10% — 30% : </strong>moderate variation</li><li><strong>above 30%</strong>: high variation</li></ul><pre>def calculate_cv(df):<br>  for column in df.columns:<br>    mean = df[column].mean()<br>    std = df[column].std()<br>    if mean != 0:<br>      cv = std / mean<br>      print(f&quot;{column}  CV = {cv}&quot;)<br>    else:<br>       print(f&quot;{column} CV cannot be calculated (mean is zero)&quot;)</pre><pre>calculate_cv(df_numerical)</pre><p>output:</p><pre>Pregnancies  CV = 0.8128107851928255<br>Glucose  CV = 0.21817537896551464<br>BloodPressure  CV = 0.14982759525230535<br>SkinThickness  CV = 0.3223108554835227<br>Insulin  CV = 0.5386098993280768<br>BMI  CV = 0.1793915785856085<br>DiabetesPedigreeFunction  CV = 0.537338405332845<br>Age  CV = 0.30356032332614563</pre><p>Pregnancies: high variation→ there are large variability in the number of pregnancies among women.</p><p>Glucose: moderate variation → there are moderate variability in Glucose levels across individuals.</p><p>BloodPressure: moderate variation → there are moderate variability in BloodPressure across individuals.</p><p>SkinThickness: high variation → there are high variability in SkinThickness across individuals.</p><p>Insulin: high variation → there are high variability in Insulin among individuals .</p><p>BMI: moderate variation→ there are moderate variability in BMI values among individuals.</p><p>DiabetesPedigreeFunction: high variation → there are large variability in DiabetesPedigreeFunction among individuals .</p><p>Age: high variation → there are high variability in age across individuals.</p><h3><strong>Inferential Statistics</strong>: Hypothesis Testing:</h3><p>Hypothesis testing: is a branch of statistic that use a sample from data to check a claim then make generalization or inference on the whole population based on it, it involves setting two opposite hypothesis:</p><p>Null Hypothesis (H0) and Alternative Hypothesis (H1 or Ha).</p><p>According to <strong>Oxford Languages</strong> dictionary: the Null Hypothesis is the hypothesis in which there is no significant difference between specified populations</p><p>Alternative Hypothesis : the claim or statement in which there <em>is</em> a significant effect, difference, or relationship between variables.</p><p>There are many types of hypothesis testing differ from each other depending on how many variables you want to include while test a claim and in which direction you need to verify your claim (like less than or greater than).</p><h4><strong>According to the number of variables we have:</strong></h4><p>Simple Hypothesis: Assumes specific relationship between one independent variable and one dependent variable.</p><p>Complex Hypothesis: Assumes relationship between multiple variables.</p><h4>According to direction of hypothesis we have :</h4><p>Directional Hypothesis: also known as a one-tailed hypothesis, is an assumption which states a specific direction of relationship or difference between variables like less than or greater than, increase or decrease, so the relationship can be positive or negative.</p><p>example: spending more time at studying leads to higher exam scores.</p><p>Non-directional Hypothesis: also known as two-tailed hypothesis assumes a relationship or difference between variables but doesn’t specify the direction.</p><p>example: there is a relationship between exam score and sleeping hours.</p><p>Another thing you should be aware of that the hypothesis can be describe according its direction and number of variables at the same time:</p><p>We can say :the hypothesis is simple (contain of two variables) and directional (study the direction of relationship).</p><p>also can be simple and non directional.</p><p>complex and directional.</p><p>complex and non directional.</p><p>As well as the hypothesis types can be describe according to the type of the focused variable in the claim ,in this case we have two types:</p><p>Mean Hypothesis: state a assumption about a numerical data to check claim about average value.</p><p>Proportion Hypothesis: set assumption about categorical data to check claim about frequency of category.</p><p>Let’s move to code:</p><h4>Simple hypothesis: Mean (Left Tailed):</h4><p><strong>The average age of patients who diagnosed with diabetes is less than 38:</strong></p><p>Before moving to code, let’s define the hypothesis:</p><p><strong>. Null hypothesis</strong>: the average age is 38.</p><p><strong>. Alternative hypothesis: </strong>The average age is less than 38</p><p>Now we will check simple mean hypothesis using one-sample t-test with alternative=’less’ as left tailed hypothesis, and pass the age of patients who were diagnosed with diabetes as a sample, and 38 as population mean (popmean), then compare the p_value with alpha:</p><p>if p_value less than alpha → reject the null hypothesis → the average age is less than 38.</p><p>if p-value lager than alpha → accept the null hypothesis → the average age is 38</p><pre>sample=df.loc[df[&#39;Outcome1&#39;]==&#39;diabetes&#39;,&#39;Age&#39;].values #define the sample by selecting the age of patients who were diagnosed diabetes.<br>hypothesized_mean=38 # define the claim mean<br>alpha = 0.05 # define significance level that represents the threshold for deciding whether to reject the null hypothesis<br># Perform the left-tailed t-test<br>t_statistic, p_value = stats.ttest_1samp(a=sample, popmean=hypothesized_mean, alternative=&#39;less&#39;)<br>print(f&quot;T-statistic: {t_statistic}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br><br>if p_value &lt; alpha:<br>    print(&quot;Result: Reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is statistically significant evidence to suggest that the average age of patients with diabetes is less than 38.&quot;)<br>else:<br>    print(&quot;Result: Fail to reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is not enough evidence to conclude that the average age of patients with diabetes is less than 38.&quot;)<br><br></pre><p>output :</p><pre>T-statistic: -2.8445572789880065<br>P-value: 0.002395822935211782<br>Result: Reject the null hypothesis.<br>Conclusion: There is statistically significant evidence to suggest that the average age of patients with diabetes is less than 38.</pre><p>the p_value of t_test is less than alpha, which support our claim :average age of patients who diagnosed with diabetes was less than 38:</p><p><em>Let’s test another claim:</em></p><p><strong>The average Glucose for patients who don’t have diabetes is less than 114</strong></p><pre>hypothesized_mean=114<br>alpha = 0.05<br>sample=df.loc[df[&#39;Outcome1&#39;]==&#39;non_diabetes&#39;,&#39;Glucose&#39;].values<br># Perform the left-tailed t-test<br>t_statistic, p_value = stats.ttest_1samp(a=sample, popmean=hypothesized_mean, alternative=&#39;less&#39;)<br>print(f&quot;T-statistic: {t_statistic}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br><br>if p_value &lt; alpha:<br>    print(&quot;Result: Reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is statistically significant evidence to suggest that the average Glucose for patients who don&#39;t have diabetes is less than 114.&quot;)<br>else:<br>    print(&quot;Result: Fail to reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is not enough evidence to conclude that the average  Glucose for patients who don&#39;t have diabetes is less than 114.&quot;)</pre><p>output:</p><pre>T-statistic: -2.787180090935373<br>P-value: 0.0027597956493428813<br>Result: Reject the null hypothesis.<br>Conclusion: There is statistically significant evidence to suggest that the average Glucose for patients who don&#39;t have diabetes is less than 114.</pre><p>Again the p_value of t_test is less than alpha, which support our claim :<strong> </strong>average Glucose for patients who don’t have diabetes is less than 114</p><h4>Simple hypothesis: Mean (Right Tailed):</h4><p><strong>Average BloodPressure for patients who have diabetes is more than 75:</strong></p><p>checking this claim is the same as the previous one except replace ‘less’ with ‘greater’ as an alternative for right tailed hypothesis.</p><pre>hypothesized_mean=75<br>alpha = 0.05<br>sample=df[df[&#39;Outcome1&#39;] == &#39;diabetes&#39;][&#39;BloodPressure&#39;].values<br># Perform the right-tailed t-test<br>t_statistic, p_value = stats.ttest_1samp(a=sample, popmean=hypothesized_mean, alternative=&#39;greater&#39;)<br>print(f&quot;T-statistic: {t_statistic}&quot;)<br>print(f&quot;P-value: {p_value}&quot;)<br><br>if p_value &lt; alpha:<br>    print(&quot;Result: Reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is statistically significant evidence to suggest that the average BloodPressure for patients who have diabetes is more than 75.&quot;)<br>else:<br>    print(&quot;Result: Fail to reject the null hypothesis.&quot;)<br>    print(&quot;Conclusion: There is not enough evidence to conclude that the average  BloodPressure for patients who have diabetes is more than 75.&quot;)</pre><p>output:</p><pre>T-statistic: -2.465641310576581<br>P-value: 0.9928469929561965<br>Result: Fail to reject the null hypothesis.<br>Conclusion: There is not enough evidence to conclude that the average  BloodPressure for patients who have diabetes is more than 75.</pre><p>the p_value of t_test is greater than alpha → accept the null hypothesis → there is no enough evidence to support our claim</p><h4>Simple hypothesis: Proportion (Right Tailed):</h4><p><strong>The proportion of patients diagnosed with diabetes is more than 30 %:</strong></p><p>Here we will used one-sample proportion z-test , which is standard and correct approach for proportion testing , z_test assumes a normal distribution based on large sample sizes (more &gt;30) based to central limit theorem, and that’s why you have to pass a large sample size. therefore we will use the full data as a sample, as it does not represent the entire population, it is itself a sample from a larger population.</p><pre>count = (df[&#39;Outcome1&#39;] == &#39;diabetes&#39;).sum()# Number of success in the sample<br>nobs=len(df) # (number of observations):the total sample size <br>p0 = 0.30 # hypothesized population proportion<br># perform one proportion z-test<br>z_statistic, p_value=proportions_ztest(count,nobs, value=p0,alternative=&#39;larger&#39;)<br><br># Print the results<br>print(f&quot;Number of pateints diagnosed with diabetes in sample: {count}&quot;)<br>print(f&quot;Total observations in data: {nobs}&quot;)<br>print(f&quot;Hypothesized proportion (p0): {p0}&quot;)<br>print(f&quot;Z-statistic: {z_statistic:.4f}&quot;)<br>print(f&quot;P-value: {p_value:.4f}&quot;)<br><br># Decide whether to reject the null hypothesis based on the p-value and significance level (alpha)<br>alpha = 0.05  #  Significance level<br><br>print(f&quot;\nSignificance level (alpha): {alpha}&quot;)<br><br>if p_value &lt; alpha:<br>    print(&quot;Conclusion: Reject the null hypothesis. There is sufficient evidence to support the claim that the proportion of  pateints diagnosed with diabetes is more than 30 %.&quot;)<br>else:<br>    print(&quot;Conclusion: Fail to reject the null hypothesis. There is not enough evidence from the sample to support the claim that the proportion of pateints diagnosed with diabetes is more than 30 %&quot;)</pre><p>output:</p><pre>Number of pateints diagnosed with diabetes in sample: 268<br>Total observations in data: 768<br>Hypothesized proportion (p0): 0.3<br>Z-statistic: 2.8465<br>P-value: 0.0022<br><br>Significance level (alpha): 0.05<br>Conclusion: Reject the null hypothesis. There is sufficient evidence to support the claim that the proportion of  pateints diagnosed with diabetes is more than 30 %.</pre><p>p-value is less than alpha → reject the null hypothesis → there is enough evidence to support our claim that the proportion of patients diagnosed with diabetes is more than 30 %</p><h4>Simple hypothesis: Mean (Two Tailed):</h4><p><strong>Is there a difference at average Insulin level between patients who were diagnosed with diabetes and those who were not.</strong></p><p>to check this claim: we conduct the independent two-sample t-test because we comparing the means of a continuous variable (Insulin) between two distinct, independent groups: those who were diagnosed with diabetes and those who were not , we will split the data into two independent groups, run the t_test with alternative = ‘two_sided’ as infernce of two tailed hypothesis, and equal_var=False because the insulin levels between the two groups likely have different variances.</p><p>Note : assign equal_var to False mean that you use <strong>Welch’s t-test ( </strong>a<strong> </strong>version of the independent t-test that does not assume equal variances).</p><pre># Split the data into two independent groups<br>insulin_diabetes = df.loc[df[&#39;Outcome1&#39;] == &#39;diabetes&#39;, &#39;Insulin&#39;]<br>insulin_non_diabetes = df.loc[df[&#39;Outcome1&#39;] == &#39;non_diabetes&#39;, &#39;Insulin&#39;]<br><br># Perform independent two-sample t-test (Welch&#39;s t-test)<br>t_statistic, p_value = stats.ttest_ind(<br>    insulin_diabetes,<br>    insulin_non_diabetes,<br>    alternative=&#39;two-sided&#39;,<br>    equal_var=False   # Welch&#39;s t-test <br>)<br><br>print(f&quot;Mean Insulin (diabetes): {insulin_diabetes.mean():.2f}&quot;)<br>print(f&quot;Mean Insulin (non_diabetes): {insulin_non_diabetes.mean():.2f}&quot;)<br>print(f&quot;T-statistic: {t_statistic:.4f}&quot;)<br>print(f&quot;P-value: {p_value:.4f}&quot;)<br>alpha = 0.05<br><br>if p_value &lt; alpha:<br>    print(&quot;Reject H₀: There is a statistically significant difference at average insulin levels.&quot;)<br>else:<br>    print(&quot;Fail to reject H₀: No statistically significant difference at average insulin levels.&quot;)</pre><p>output:</p><pre>Mean Insulin (diabetes): 112.22<br>Mean Insulin (non_diabetes): 91.27<br>T-statistic: 5.0136<br>P-value: 0.0000<br>Reject H₀: There is a statistically significant difference at average insulin levels.</pre><p>p_value=0.0000 that is less than alpha →highly significant (reject the null hypothesis)→ we have very strong evidence to conclude that there is statistically significant difference exists at average Insulin level between patients who were diagnosed with diabetes and those who were not</p><h4>Simple hypothesis: proportion (Two Tailed):</h4><p><strong>The proportion of patients who were not diagnosed with diabetes is different from 50%.</strong></p><p>check this claim using z_test with passing alternative =’two-sided’</p><pre>count = (df[&#39;Outcome1&#39;] == &#39;non_diabetes&#39;).sum()# Number of success in the sample<br>nobs=len(df)# (number of observations):the total sample size<br>p0 = 0.50<br># perform one proportion z-test<br>z_statistic, p_value=proportions_ztest(count,nobs, value=p0,alternative=&#39;two-sided&#39;)<br><br># Print the results<br>print(f&quot;Number of pateints who were not  diagnosed with diabetes in sample: {count}&quot;)<br>print(f&quot;Total observations in data: {nobs}&quot;)<br>print(f&quot;Hypothesized proportion (p0): {p0}&quot;)<br>print(f&quot;Z-statistic: {z_statistic:.4f}&quot;)<br>print(f&quot;P-value: {p_value:.4f}&quot;)<br><br># Decide whether to reject the null hypothesis based on the p-value and significance level (alpha)<br>alpha = 0.05  #  Significance level<br><br>print(f&quot;\nSignificance level (alpha): {alpha}&quot;)<br><br>if p_value &lt; alpha:<br>    print(&quot;Conclusion: Reject the null hypothesis. There is sufficient evidence to support the claim that the proportion of  pateints who were not diagnosed with diabetes is more than 50 %.&quot;)<br>else:<br>    print(&quot;Conclusion: Fail to reject the null hypothesis. There is not enough evidence from the sample to support the claim that the proportion of pateints who were not diagnosed with diabetes is more than 50 %&quot;)</pre><p>output:</p><pre>Number of pateints who were not  diagnosed with diabetes in sample: 500<br>Total observations in data: 768<br>Hypothesized proportion (p0): 0.5<br>Z-statistic: 8.7819<br>P-value: 0.0000<br><br>Significance level (alpha): 0.05<br>Conclusion: Reject the null hypothesis. There is sufficient evidence to support the claim that the proportion of  pateints who were not diagnosed with diabetes is more than 50 %</pre><p>p_value =0.0 less than alpha → reject the null hypothesis → we have strong evidence to support our claim.</p><h4>Conclusion</h4><p>This story demonstrated the importance of understanding descriptive and inferential statistical concepts .</p><p>Measures of central tendency (mean, median, and mode) were interpreted in relation to distribution shape and modality , also variability was examined using standard deviation, variance, with highlighting the using of coefficient of variation (CV) as a trust way to judge about variability.</p><p>We also threw light<strong> </strong>on hypothesis testing as a branch of Inferential Statistic, with focusing in its types including simple and complex hypothesis, directional and non-directional claims, and tests concerning both means and proportions</p><p>Overall, this story illustrates that proper statistical analysis requires careful consideration of distribution characteristics, variability measures, hypothesis structure, and appropriate test selection.</p><p>If you need any further information, don’t hesitate to contact, and share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f1c1e4db710" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Methods: A Guided Approach To Master Data Analysis.]]></title>
            <link>https://medium.com/@engulayousef99/pandas-methods-query-about-your-data-like-a-hero-6b6f1b9951f8?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6f1b9951f8</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-querying]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 13:51:49 GMT</pubDate>
            <atom:updated>2025-03-13T18:02:09.743Z</atom:updated>
            <content:encoded><![CDATA[<p>Wise man said: “pandas are peaceful animals” and after that his life has changed forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LnmZPm-8Jaoff1hqFTdDGA.jpeg" /><figcaption>image from Pixabay</figcaption></figure><p>I will feel sad for people who say they are afraid of panda, but i laugh at python’s programmer if he says the same thing. What motivates me to say this is Pandas library, counter to Panda bears which sometimes can be dangerous when they are infuriated or frightened. Pandas library is one of the most friendly basic in data field for many reasons</p><p>flexibility, easy to learn and easy to apply.</p><p>Let’s take a quick tour about pandas:</p><p>1_ Stands for Panel Data and Python Data Analysis.</p><p>2_ Most popular library for data manipulation and data analysis in python.</p><p>3_ Has the ability to read and write to specific source like(csv, excel, html, SQL).</p><p>4_ Use an expressive data structure called ‘Data Frames’ that represents data in a tabular format.</p><p>5_ Powerful grouping and sorting operations within the data.</p><p>In this story we will work on pandas data frame which is the main tool in pandas, it is a table of columns and rows, each column and row is a pandas series so it a list of series that share index, we will use Fuel_Consumption_2000–2022 data set from Kaggle, this data provides model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada.</p><p>This story will be divide into two sections :</p><p>1_ applying pandas methods.</p><p>2_ querying about data using pandas.</p><p>Now let’s start with the first section:</p><h4>import libraries:</h4><pre>import pandas as pd<br>import numpy as np</pre><h4>data set reading:</h4><pre>df=pd.read_csv(&#39;/content/Fuel_Consumption_2000-2022.csv&#39;)</pre><h4>checking the upper limit of the data, display the first 10 rows present in the data frame</h4><pre>df.head(10)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYzN6gLEmseAdX4YyyUSJA.png" /></figure><p>we have 13 attributes which are:</p><p>YEAR, MAKE, MODEL, VEHICLE CLASS, ENGINE SIZE, CYLINDERS, TRANSMISSIONS, FUEL, FUEL CONSUMPTION, HWY (L/100 km), COMB (L/100 km), COMB(mpg),EMISSIONS.</p><p>Here are the details of ambiguous attributes from Kaggle:</p><blockquote><strong>Model</strong></blockquote><blockquote>4WD/4X4 = Four-wheel drive</blockquote><blockquote>AWD = All-wheel drive</blockquote><blockquote>CNG = Compressed natural gas</blockquote><blockquote>FFV = Flexible-fuel vehicle</blockquote><blockquote>NGV = Natural gas vehicle</blockquote><blockquote># = High output engine that provides more power than the standard engine of the same size</blockquote><blockquote><strong>Transmission</strong></blockquote><blockquote>A = Automatic</blockquote><blockquote>AM = Automated manual</blockquote><blockquote>AS = Automatic with select shift</blockquote><blockquote>AV = Continuously variable</blockquote><blockquote>M = Manual<br>3–10 = Number of gears<em><br></em><strong>Fuel Type</strong></blockquote><blockquote>X = Regular gasoline</blockquote><blockquote>Z = Premium gasoline</blockquote><blockquote>D = Diesel</blockquote><blockquote>E = Ethanol (E85)</blockquote><blockquote>N = Natural Gas</blockquote><blockquote>Fuel Consumption<br>City and highway fuel consumption ratings are shown in litres per 100 kilometres (L/100 km) — combined rating (55% city, 45% hwy) is shown in L/100 km and in miles per imperial gallon (mpg)<br>CO2 Emissions (g/km),Estimated tailpipe carbon dioxide emissions (in grams per kilometre) are based on fuel type and the combined fuel consumption rating.</blockquote><h4>checking the lower limit of the data, display the last 10 rows:</h4><pre>df.tail(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTueTSrbZfaUsSPH_zJhMQ.png" /></figure><p>as the last index of row is 22555 then we have 22556 examples of each attribute (column), but why 22556 ?</p><p>because the index of rows in data frame always starts from zero while the index of columns starts from one, you can check that by take another look at the output of head method.</p><h4>checking the shape:</h4><p>instead of count the numbers of columns on your finger and apply head and tail to know the numbers of rows you can use shape method like the following :</p><pre>df.shape</pre><pre>(22556, 13)</pre><p>22556 is the numbers of rows</p><p>13 is the numbers of columns.</p><h4>summary statistics of the data frame:</h4><pre>df.describe()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*KAn2mjfltOpHgNn7iUNPPQ.png" /></figure><p>the describe method gives us a statistics information about numerical columns like: count, mean, standard deviation (std), min, 25th percentile (25%), Median value (50th percentile)(50%), 75th percentile(75%), and max value.</p><p>we can explore the range of each attribute by looking at the min and max of it:</p><p>YEAR value ranges from 2000 to 2022.</p><p>ENGINE SIZE value ranges from 0.8 to 8.4</p><p>CYLINDERS value ranges from 2.0 to 16.0</p><p>FUEL CONSUMPTION value ranges from 3.5 to 30.6</p><p>HMY (L/100 km) value ranges from 3.2 to 20.9</p><p>COMB (L/100 km) value ranges from 3.6 to 26.1</p><p>COMB (mpg) value ranges from 11.0 to 78.0</p><p>EMISSIONS value ranges from 83.0 to 608.0</p><h4>information about the data frame</h4><pre>df.info()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*hlk2-TGWX5qUPGUCFksXbA.png" /></figure><p>this method is very useful, just run a one code line and you will get a lot of details like number of non-Null values, type, label of each column, number of columns, and memory usage of data, so using info() method can safe your time from calling df.columns, df.dtypes, df.isnull().sum().</p><p>hints from info():</p><p>there are no missing values because the number of non-Null count equaled to 22556 which is the total number of examples.</p><h4>checking the type of the columns:</h4><pre>df.dtypes</pre><p>output:</p><pre>YEAR                  int64<br>MAKE                 object<br>MODEL                object<br>VEHICLE CLASS        object<br>ENGINE SIZE         float64<br>CYLINDERS             int64<br>TRANSMISSION         object<br>FUEL                 object<br>FUEL CONSUMPTION    float64<br>HWY (L/100 km)      float64<br>COMB (L/100 km)     float64<br>COMB (mpg)            int64<br>EMISSIONS             int64<br>dtype: object</pre><h4>return label of each columns:</h4><pre>df.columns</pre><p>output:</p><pre>Index([&#39;YEAR&#39;, &#39;MAKE&#39;, &#39;MODEL&#39;, &#39;VEHICLE CLASS&#39;, &#39;ENGINE SIZE&#39;, &#39;CYLINDERS&#39;,<br>       &#39;TRANSMISSION&#39;, &#39;FUEL&#39;, &#39;FUEL CONSUMPTION&#39;, &#39;HWY (L/100 km)&#39;,<br>       &#39;COMB (L/100 km)&#39;, &#39;COMB (mpg)&#39;, &#39;EMISSIONS&#39;],<br>      dtype=&#39;object&#39;)</pre><h4>checking the index of data frame:</h4><pre>df.index</pre><p>output:</p><pre>RangeIndex(start=0, stop=22556, step=1)</pre><p>return info about index (start, stop, step)</p><h3><strong>Second section: data querying</strong></h3><h4>unique value of MAKE column (company name):</h4><pre>df[&#39;MAKE&#39;].unique()</pre><p>output:</p><pre><br>array([&#39;ACURA&#39;, &#39;AUDI&#39;, &#39;BMW&#39;, &#39;BUICK&#39;, &#39;CADILLAC&#39;, &#39;CHEVROLET&#39;,<br>       &#39;CHRYSLER&#39;, &#39;DAEWOO&#39;, &#39;DODGE&#39;, &#39;FERRARI&#39;, &#39;FORD&#39;, &#39;GMC&#39;, &#39;HONDA&#39;,<br>       &#39;HYUNDAI&#39;, &#39;INFINITI&#39;, &#39;ISUZU&#39;, &#39;JAGUAR&#39;, &#39;JEEP&#39;, &#39;KIA&#39;,<br>       &#39;LAND ROVER&#39;, &#39;LEXUS&#39;, &#39;LINCOLN&#39;, &#39;MAZDA&#39;, &#39;MERCEDES-BENZ&#39;,<br>       &#39;NISSAN&#39;, &#39;OLDSMOBILE&#39;, &#39;PLYMOUTH&#39;, &#39;PONTIAC&#39;, &#39;PORSCHE&#39;, &#39;SAAB&#39;,<br>       &#39;SATURN&#39;, &#39;SUBARU&#39;, &#39;SUZUKI&#39;, &#39;TOYOTA&#39;, &#39;VOLKSWAGEN&#39;, &#39;VOLVO&#39;,<br>       &#39;BENTLEY&#39;, &#39;ROLLS-ROYCE&#39;, &#39;MASERATI&#39;, &#39;MINI&#39;, &#39;MITSUBISHI&#39;,<br>       &#39;SMART&#39;, &#39;HUMMER&#39;, &#39;ASTON MARTIN&#39;, &#39;LAMBORGHINI&#39;, &#39;BUGATTI&#39;,<br>       &#39;SCION&#39;, &#39;FIAT&#39;, &#39;RAM&#39;, &#39;SRT&#39;, &#39;ALFA ROMEO&#39;, &#39;GENESIS&#39;, &#39;Acura&#39;,<br>       &#39;Alfa Romeo&#39;, &#39;Aston Martin&#39;, &#39;Audi&#39;, &#39;Bentley&#39;, &#39;Bugatti&#39;,<br>       &#39;Buick&#39;, &#39;Cadillac&#39;, &#39;Chevrolet&#39;, &#39;Chrysler&#39;, &#39;Dodge&#39;, &#39;Ford&#39;,<br>       &#39;Genesis&#39;, &#39;Honda&#39;, &#39;Hyundai&#39;, &#39;Infiniti&#39;, &#39;Jaguar&#39;, &#39;Jeep&#39;, &#39;Kia&#39;,<br>       &#39;Lamborghini&#39;, &#39;Land Rover&#39;, &#39;Lexus&#39;, &#39;Lincoln&#39;, &#39;Maserati&#39;,<br>       &#39;Mazda&#39;, &#39;Mercedes-Benz&#39;, &#39;Mitsubishi&#39;, &#39;Nissan&#39;, &#39;Porsche&#39;, &#39;Ram&#39;,<br>       &#39;Rolls-Royce&#39;, &#39;Subaru&#39;, &#39;Toyota&#39;, &#39;Volkswagen&#39;, &#39;Volvo&#39;],<br>      dtype=object)</pre><p>this method return a numpy array of unique value in a specific column</p><p><strong><em>hint</em></strong>: some company name sometimes written as a uppercase and sometimes as a lowercase ( ex: VOLVO, Volvo, Nissan, NISSAN, Audi, AUDI)</p><p>to fix this error you have two options:</p><p><strong>either</strong>: use str.lower() to convert all uppercase letters to lowercase.</p><p><strong>or: </strong>use str.upper() to convert all lowercase letters to uppercase.</p><pre>df[&#39;MAKE&#39;]=df[&#39;MAKE&#39;].str.upper()</pre><p>let’s check the unique values of MAKE column again:</p><pre>df[&#39;MAKE&#39;].unique()</pre><p>output:</p><pre>array([&#39;ACURA&#39;, &#39;AUDI&#39;, &#39;BMW&#39;, &#39;BUICK&#39;, &#39;CADILLAC&#39;, &#39;CHEVROLET&#39;,<br>       &#39;CHRYSLER&#39;, &#39;DAEWOO&#39;, &#39;DODGE&#39;, &#39;FERRARI&#39;, &#39;FORD&#39;, &#39;GMC&#39;, &#39;HONDA&#39;,<br>       &#39;HYUNDAI&#39;, &#39;INFINITI&#39;, &#39;ISUZU&#39;, &#39;JAGUAR&#39;, &#39;JEEP&#39;, &#39;KIA&#39;,<br>       &#39;LAND ROVER&#39;, &#39;LEXUS&#39;, &#39;LINCOLN&#39;, &#39;MAZDA&#39;, &#39;MERCEDES-BENZ&#39;,<br>       &#39;NISSAN&#39;, &#39;OLDSMOBILE&#39;, &#39;PLYMOUTH&#39;, &#39;PONTIAC&#39;, &#39;PORSCHE&#39;, &#39;SAAB&#39;,<br>       &#39;SATURN&#39;, &#39;SUBARU&#39;, &#39;SUZUKI&#39;, &#39;TOYOTA&#39;, &#39;VOLKSWAGEN&#39;, &#39;VOLVO&#39;,<br>       &#39;BENTLEY&#39;, &#39;ROLLS-ROYCE&#39;, &#39;MASERATI&#39;, &#39;MINI&#39;, &#39;MITSUBISHI&#39;,<br>       &#39;SMART&#39;, &#39;HUMMER&#39;, &#39;ASTON MARTIN&#39;, &#39;LAMBORGHINI&#39;, &#39;BUGATTI&#39;,<br>       &#39;SCION&#39;, &#39;FIAT&#39;, &#39;RAM&#39;, &#39;SRT&#39;, &#39;ALFA ROMEO&#39;, &#39;GENESIS&#39;],<br>      dtype=object)</pre><h4>unique value of MODEL column:</h4><pre>df[&#39;MODEL&#39;].unique()</pre><p>output:</p><pre>array([&#39;1.6EL&#39;, &#39;3.2TL&#39;, &#39;3.5RL&#39;, ..., &#39;V90 CC B6 AWD&#39;, &#39;XC60 B5 AWD&#39;,<br>       &#39;XC60 B6 AWD&#39;], dtype=object)</pre><p>convert all letters to uppercase:</p><pre>df[&#39;MODEL&#39;]=df[&#39;MODEL&#39;].str.upper()</pre><h4>exploring the value-counts of MODEL column:</h4><pre>df[&#39;MODEL&#39;].value_counts()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*ZXEaeoHwRTu_fvePCu2JuQ.png" /></figure><p>this method returns how many times the unique value repeat in a specific column, for example JETTA model has been repeated 110 times.</p><h4>unique value of VEHICLE CLASS :</h4><pre>df[&#39;VEHICLE CLASS&#39;].unique()</pre><p>output:</p><pre>array([&#39;COMPACT&#39;, &#39;MID-SIZE&#39;, &#39;SUBCOMPACT&#39;, &#39;STATION WAGON - MID-SIZE&#39;,<br>       &#39;MINICOMPACT&#39;, &#39;TWO-SEATER&#39;, &#39;STATION WAGON - SMALL&#39;, &#39;FULL-SIZE&#39;,<br>       &#39;SUV&#39;, &#39;VAN - CARGO&#39;, &#39;VAN - PASSENGER&#39;, &#39;PICKUP TRUCK - STANDARD&#39;,<br>       &#39;PICKUP TRUCK - SMALL&#39;, &#39;MINIVAN&#39;, &#39;SUV - STANDARD&#39;,<br>       &#39;SPECIAL PURPOSE VEHICLE&#39;, &#39;SUV - SMALL&#39;, &#39;Compact&#39;, &#39;SUV: Small&#39;,<br>       &#39;Two-seater&#39;, &#39;Mid-size&#39;, &#39;Minicompact&#39;, &#39;Subcompact&#39;,<br>       &#39;Station wagon: Small&#39;, &#39;Full-size&#39;, &#39;SUV: Standard&#39;,<br>       &#39;Special purpose vehicle&#39;, &#39;Pickup truck: Small&#39;,<br>       &#39;Pickup truck: Standard&#39;, &#39;Minivan&#39;, &#39;Van: Passenger&#39;,<br>       &#39;Station wagon: Mid-size&#39;], dtype=object)</pre><p>hint: values written in two different ways like: Minivan, MINIVAN</p><p>need to unify the writing type:</p><pre>df[&#39;VEHICLE CLASS&#39;]=df[&#39;VEHICLE CLASS&#39;].str.lower()<br>df[&#39;VEHICLE CLASS&#39;]</pre><p>output:</p><pre>array([&#39;compact&#39;, &#39;mid-size&#39;, &#39;subcompact&#39;, &#39;station wagon - mid-size&#39;,<br>       &#39;minicompact&#39;, &#39;two-seater&#39;, &#39;station wagon - small&#39;, &#39;full-size&#39;,<br>       &#39;suv&#39;, &#39;van - cargo&#39;, &#39;van - passenger&#39;, &#39;pickup truck - standard&#39;,<br>       &#39;pickup truck - small&#39;, &#39;minivan&#39;, &#39;suv - standard&#39;,<br>       &#39;special purpose vehicle&#39;, &#39;suv - small&#39;, &#39;suv: small&#39;,<br>       &#39;station wagon: small&#39;, &#39;suv: standard&#39;, &#39;pickup truck: small&#39;,<br>       &#39;pickup truck: standard&#39;, &#39;van: passenger&#39;,<br>       &#39;station wagon: mid-size&#39;], dtype=object)</pre><h4>checking unique value of FUEL:</h4><pre>df[&#39;FUEL&#39;].unique()</pre><p>output:</p><pre>array([&#39;X&#39;, &#39;Z&#39;, &#39;E&#39;, &#39;N&#39;, &#39;D&#39;], dtype=object)</pre><h4>number of iteration for each FUEL type:</h4><pre>df[&#39;FUEL&#39;].value_counts()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*JiFRn2XfhmfreQGUAxhI2g.png" /></figure><h4>checking unique value of TRANSMISSION:</h4><pre>df[&#39;TRANSMISSION&#39;].unique()</pre><p>output:</p><pre>array([&#39;A4&#39;, &#39;M5&#39;, &#39;AS5&#39;, &#39;AS4&#39;, &#39;M6&#39;, &#39;A5&#39;, &#39;A3&#39;, &#39;AS6&#39;, &#39;AV&#39;, &#39;A6&#39;,<br>       &#39;AM6&#39;, &#39;A7&#39;, &#39;AM7&#39;, &#39;AS7&#39;, &#39;AS8&#39;, &#39;M4&#39;, &#39;A8&#39;, &#39;M7&#39;, &#39;AV7&#39;, &#39;AV8&#39;,<br>       &#39;AV6&#39;, &#39;AM5&#39;, &#39;A9&#39;, &#39;AS9&#39;, &#39;AM8&#39;, &#39;AM9&#39;, &#39;AS10&#39;, &#39;A10&#39;, &#39;AV10&#39;,<br>       &#39;AV1&#39;], dtype=object)</pre><h4>finding missing data:</h4><pre>df.isnull().sum()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*Zh8kGbnhXk_jXmzN-HgTTg.png" /></figure><h4>finding duplicated values:</h4><pre>df.duplicated().sum()</pre><p>output:</p><pre>1</pre><h4>dropping the duplicated rows:</h4><pre>df.drop_duplicates(inplace=True)</pre><h4>querying about specific label of MAKE, for example get info about LAND ROVER:</h4><pre>df[df[&#39;MAKE&#39;]==&#39;LAND ROVER&#39;]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUYJ0VXo9mouuvgkVbiySA.png" /></figure><p>Hint: we have 173 examples of LAND ROVER.</p><p>Another way you can use to query about specific label of column is: df.loc</p><pre>df.loc[df[&#39;MAKE&#39;]==&#39;LAND ROVER&#39;]</pre><p>and we will get the same output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fQ4ygC_SIOJBSpOIClqGw.png" /></figure><h4>manufacturing year for specific MAKE (e.g. VOLVO)</h4><pre>df[df[&#39;MAKE&#39;]==&#39;VOLVO&#39;].YEAR.unique()</pre><p>output:</p><pre>array([2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,<br>       2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021,<br>       2022])</pre><h4>let’s do the same thing for DAEWOO:</h4><pre>df[df[&#39;MAKE&#39;]==&#39;DAEWOO&#39;].YEAR.unique()</pre><p>output:</p><pre>array([2000, 2001, 2002])</pre><p>but if we want to do that for all company?, it will be hard to repeat the same code, instead we will write a function to return the manufacturing year for each company:</p><pre>def productiom_date_of_car(df,column):<br>    for i  in column.unique():<br>        j=df[column==i].YEAR.unique()<br>        print(&quot;the production date of {make} is:{p}&quot;.format(make=i, p=j))<br>        print(&#39;\t&#39;)</pre><p>we pass the column and data frame as an input to the function, loop over the unique value of MAKE column then return the unique value of YEAR for each unique value of MAKE , finally print the output .</p><p>Let’s call the function for MAKE column:</p><pre>productiom_date_of_car (df,df[&#39;MAKE&#39;])</pre><p>output:</p><pre>the production date of ACURA is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of AUDI is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of BMW is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of BUICK is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of CADILLAC is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of CHEVROLET is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of CHRYSLER is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of DAEWOO is:[2000 2001 2002]<br> <br>the production date of DODGE is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of FERRARI is:[2000 2002 2003 2004 2005 2006 2007 2008 2009 2010]<br> <br>the production date of FORD is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of GMC is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of HONDA is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of HYUNDAI is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of INFINITI is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of ISUZU is:[2000 2001 2002 2003]<br> <br>the production date of JAGUAR is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of JEEP is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of KIA is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of LAND ROVER is:[2000 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014<br> 2015 2016 2017 2018 2019 2020 2022]<br> <br>the production date of LEXUS is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of LINCOLN is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of MAZDA is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of MERCEDES-BENZ is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of NISSAN is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of OLDSMOBILE is:[2000 2001 2002 2003 2004]<br> <br>the production date of PLYMOUTH is:[2000 2001]<br> <br>the production date of PONTIAC is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010]<br> <br>the production date of PORSCHE is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of SAAB is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009]<br> <br>the production date of SATURN is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009]<br> <br>the production date of SUBARU is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of SUZUKI is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013]<br> <br>the production date of TOYOTA is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of VOLKSWAGEN is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of VOLVO is:[2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013<br> 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of BENTLEY is:[2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015<br> 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of ROLLS-ROYCE is:[2002 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016<br> 2017 2018 2019 2020 2021 2022]<br> <br>the production date of MASERATI is:[2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016<br> 2017 2018 2019 2020 2021 2022]<br> <br>the production date of MINI is:[2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016<br> 2017 2018 2019 2020 2021 2022]<br> <br>the production date of MITSUBISHI is:[2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016<br> 2017 2018 2019 2020 2021 2022]<br> <br>the production date of SMART is:[2005 2006 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017]<br> <br>the production date of HUMMER is:[2006 2007 2008 2009 2010]<br> <br>the production date of ASTON MARTIN is:[2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020<br> 2021 2022]<br> <br>the production date of LAMBORGHINI is:[2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020<br> 2021 2022]<br> <br>the production date of BUGATTI is:[2010 2011 2012 2018 2019 2020 2021 2022]<br> <br>the production date of SCION is:[2011 2012 2013 2014 2015 2016]<br> <br>the production date of FIAT is:[2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of RAM is:[2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of SRT is:[2013 2014]<br> <br>the production date of ALFA ROMEO is:[2014 2015 2016 2017 2018 2019 2020 2021 2022]<br> <br>the production date of GENESIS is:[2017 2018 2019 2020 2021 2022]</pre><h4>MODEL (car model) for specific MAKE (company):</h4><pre>df.loc[(df.MAKE==&#39;NISSAN&#39;),&#39;MODEL&#39;].unique()</pre><p>output:</p><pre>array([&#39;ALTIMA&#39;, &#39;FRONTIER&#39;, &#39;FRONTIER 4X4&#39;, &#39;FRONTIER V6&#39;,<br>       &#39;FRONTIER V6 4X4&#39;, &#39;MAXIMA&#39;, &#39;PATHFINDER 4X4&#39;, &#39;QUEST&#39;, &#39;XTERRA&#39;,<br>       &#39;XTERRA V6&#39;, &#39;XTERRA V6 4X4&#39;, &#39;FRONTIER V6 #&#39;, &#39;FRONTIER V6 4X4 #&#39;,<br>       &#39;SENTRA&#39;, &#39;XTERRA V6 4X4 #&#39;, &#39;350Z&#39;, &#39;MURANO AWD&#39;, &#39;350Z ROADSTER&#39;,<br>       &#39;MURANO&#39;, &#39;PATHFINDER ARMADA 4X4&#39;, &#39;TITAN&#39;, &#39;TITAN 4X4&#39;, &#39;350Z #&#39;,<br>       &#39;ARMADA 4X4&#39;, &#39;X-TRAIL&#39;, &#39;X-TRAIL AWD&#39;, &#39;350Z ROADSTER #&#39;,<br>       &#39;XTERRA 4X4&#39;, &#39;ALTIMA HYBRID&#39;, &#39;VERSA&#39;, &#39;ALTIMA COUPE&#39;, &#39;ROGUE&#39;,<br>       &#39;ROGUE AWD&#39;, &#39;370Z COUPE&#39;, &#39;GT-R TURBO&#39;, &#39;370Z&#39;, &#39;370Z ROADSTER&#39;,<br>       &#39;ARMADA 4WD&#39;, &#39;CUBE&#39;, &#39;FRONTIER 4WD&#39;, &#39;GT-R&#39;, &#39;PATHFINDER 4WD&#39;,<br>       &#39;TITAN 4WD&#39;, &#39;XTERRA 4WD&#39;, &#39;JUKE&#39;, &#39;JUKE AWD&#39;, &#39;NV200 CARGO VAN&#39;,<br>       &#39;PATHFINDER&#39;, &#39;PATHFINDER HYBRID 4WD&#39;, &#39;JUKE NISMO RS&#39;,<br>       &#39;JUKE NISMO RS AWD&#39;, &#39;MICRA&#39;, &#39;PATHFINDER 4WD PLATINUM&#39;,<br>       &#39;ALTIMA 3.5&#39;, &#39;ALTIMA SR&#39;, &#39;QASHQAI&#39;, &#39;QASHQAI AWD&#39;,<br>       &#39;SENTRA (TURBO)&#39;, &#39;SENTRA NISMO&#39;, &#39;TITAN 4WD PRO-4X&#39;, &#39;KICKS&#39;,<br>       &#39;ALTIMA SR/PLATINUM&#39;, &#39;ALTIMA AWD&#39;, &#39;ALTIMA AWD SR/PLATINUM&#39;,<br>       &#39;SENTRA SR&#39;, &#39;ROGUE AWD SL/PLATINUM&#39;], dtype=object)</pre><h4>try the same thing for MAZDA:</h4><pre>df.loc[(df.MAKE==&#39;MAZDA&#39;),&#39;MODEL&#39;].unique()</pre><p>output:</p><pre>array([&#39;626&#39;, &#39;B3000&#39;, &#39;B4000&#39;, &#39;B4000 4X4&#39;, &#39;MILLENIA&#39;, &#39;MILLENIA #&#39;,<br>       &#39;MPV&#39;, &#39;MX-5 MIATA&#39;, &#39;PROTEGE&#39;, &#39;TRIBUTE&#39;, &#39;TRIBUTE 4X4&#39;,<br>       &#39;PROTEGE/PROTEGE5&#39;, &#39;B2300&#39;, &#39;B3000 FFV&#39;,<br>       &#39;MAZDASPEED PROTEGE TURBO&#39;, &#39;MAZDA3&#39;, &#39;MAZDA6&#39;, &#39;RX-8&#39;,<br>       &#39;MAZDA6 SPORT WAGON&#39;, &#39;MAZDASPEED MX-5 TURBO&#39;, &#39;MAZDA5 WAGON&#39;,<br>       &#39;MAZDA6 TURBO&#39;, &#39;MX-5&#39;, &#39;CX-7 TURBO&#39;, &#39;MAZDA3 TURBO&#39;, &#39;MAZDA5&#39;,<br>       &#39;CX-7 4X4 TURBO&#39;, &#39;CX-9&#39;, &#39;CX-9 4X4&#39;, &#39;MAZDASPEED 3 TURBO&#39;,<br>       &#39;TRIBUTE AWD&#39;, &#39;MAZDASPEED3 TURBO&#39;, &#39;CX-7&#39;, &#39;CX-7 4WD&#39;, &#39;CX-9 4WD&#39;,<br>       &#39;MAZDASPEED3&#39;, &#39;TRIBUTE 4X4 FFV&#39;, &#39;TRIBUTE FFV&#39;, &#39;MAZDA2&#39;,<br>       &#39;MAZDA3 DI 4-DOOR&#39;, &#39;MAZDA3 DI 5-DOOR&#39;, &#39;CX-5&#39;, &#39;CX-5 4WD&#39;,<br>       &#39;MAZDA3 L5X&#39;, &#39;MAZDA3 LFX&#39;, &#39;MAZDA3 4-DOOR&#39;,<br>       &#39;MAZDA3 4-DOOR (I-ELOOP)&#39;, &#39;MAZDA3 4-DOOR (SIL)&#39;, &#39;MAZDA3 5-DOOR&#39;,<br>       &#39;MAZDA3 5-DOOR (I-ELOOP)&#39;, &#39;MAZDA3 5-DOOR (SIL)&#39;,<br>       &#39;MAZDA6 (I-ELOOP)&#39;, &#39;CX-3&#39;, &#39;CX-3 4WD&#39;, &#39;CX-5 (SIL)&#39;,<br>       &#39;MAZDA6 (SIL)&#39;, &#39;MX-5 (SIL)&#39;, &#39;CX-5 &#39;,<br>       &#39;CX-5 (CYLINDER DEACTIVATION)&#39;, &#39;CX-5 4WD (CYLINDER DEACTIVATION)&#39;,<br>       &#39;CX-5 TURBO 4WD&#39;, &#39;CX-5 DIESEL 4WD&#39;,<br>       &#39;MAZDA3 4-DOOR (CYLINDER DEACTIVATION)&#39;, &#39;MAZDA3 4-DOOR 4WD&#39;,<br>       &#39;MAZDA3 5-DOOR 4WD&#39;, &#39;CX-3 (SIL)&#39;, &#39;CX-30&#39;, &#39;CX-30 4WD&#39;,<br>       &#39;CX-30 4WD (CYLINDER DEACTIVATION)&#39;, &#39;CX-30 TURBO 4WD&#39;,<br>       &#39;MAZDA3 4-DOOR TURBO 4WD&#39;, &#39;MAZDA3 5-DOOR TURBO 4WD&#39;], dtype=object)</pre><h4>checking the unique value of VEHICLE CLASS for each MAKE</h4><pre>df.groupby(&#39;MAKE&#39;)[&#39;VEHICLE CLASS&#39;].unique()</pre><p>groupby() allows to group together rows based on a column then perform aggregate function on them, in the previous code we use groupby() to group the data by MAKE and return the unique value of VEHICLE CLASS for each MAKE (company).</p><p>output:</p><pre>                           VEHICLE CLASS<br>MAKE <br>ACURA          [compact, mid-size, subcompact, suv, two-seate...<br>ALFA ROMEO     [two-seater, mid-size, suv: small]<br>ASTON MARTIN   [minicompact, two-seater, subcompact, suv: sta...<br>AUDI           [compact, mid-size, station wagon - mid-size, ...<br>BENTLEY        [full-size, mid-size, subcompact, compact, two...<br>BMW            [compact, station wagon - small, mid-size, ful...<br>BUGATTI        [two-seater]<br>BUICK          [mid-size, full-size, suv, minivan, suv - stan...<br>CADILLAC       [mid-size, full-size, suv, pickup truck - stan...<br>CHEVROLET      [van - cargo, van - passenger, suv, pickup tru...<br>CHRYSLER       [full-size, mid-size, compact, subcompact, min...<br>DAEWOO         [subcompact, compact, station wagon - small, m...<br>DODGE          [minivan, pickup truck - standard, suv, van - ...<br>FERRARI        [two-seater, subcompact, mid-size]<br>FIAT           [minicompact, station wagon - small, suv - sma...<br>FORD           [compact, full-size, van - passenger, van - ca...<br>GENESIS        [full-size, compact, suv: standard, suv: small]<br>GMC            [pickup truck - standard, suv, van - cargo, va...<br>HONDA          [mid-size, subcompact, suv, minivan, compact, ...<br>HUMMER         [suv, pickup truck - standard]<br>HYUNDAI        [compact, station wagon - small, mid-size, sub...<br>INFINITI       [compact, mid-size, suv, full-size, subcompact...<br>ISUZU          [pickup truck - small, pickup truck - standard...<br>JAGUAR         [mid-size, compact, subcompact, minicompact, f...<br>JEEP           [suv, subcompact, suv - small, suv - standard,...<br>KIA            [compact, suv, subcompact, mid-size, minivan, ...<br>LAMBORGHINI    [two-seater, suv: standard]<br>LAND ROVER     [suv, suv - small, suv - standard, suv: small,...<br>LEXUS          [compact, mid-size, suv, subcompact, full-size...<br>LINCOLN        [full-size, mid-size, suv, pickup truck - stan...<br>MASERATI       [two-seater, subcompact, full-size, mid-size, ...<br>MAZDA          [mid-size, pickup truck - standard, compact, m...<br>MERCEDES-BENZ  [compact, subcompact, minicompact, mid-size, s...<br>MINI           [minicompact, subcompact, compact, two-seater,...<br>MITSUBISHI     [subcompact, minicompact, mid-size, compact, s...<br>NISSAN         [compact, pickup truck - standard, mid-size, s...<br>OLDSMOBILE     [compact, mid-size, minivan, suv]<br>PLYMOUTH       [subcompact, two-seater]<br>PONTIAC        [full-size, subcompact, compact, mid-size, min...<br>PORSCHE        [minicompact, two-seater, suv, full-size, suv ...<br>RAM            [pickup truck - standard, minivan, special pur...<br>ROLLS-ROYCE    [subcompact, full-size, mid-size, compact, sta...<br>SAAB           [mid-size, full-size, station wagon - mid-size...<br>SATURN         [mid-size, station wagon - mid-size, subcompac...<br>SCION          [compact, station wagon - small, subcompact, m...<br>SMART          [two-seater]<br>SRT            [two-seater]<br>SUBARU         [suv, subcompact, station wagon - small, compa...<br>SUZUKI         [subcompact, station wagon - small, suv, compa...<br>TOYOTA         [suv, full-size, mid-size, compact, subcompact...<br>VOLKSWAGEN     [subcompact, minivan, compact, mid-size, stati...<br>VOLVO          [subcompact, compact, mid-size, station wagon ...<br>dtype: object</pre><p>the output is not clear enough, we have a lot of VEHICLE CLASS values for each company, so we will perform a simple trick to make the results more regular.</p><h4>checking the unique value of VEHICLE CLASS for each MAKE (company) with describe() method:</h4><pre>df.groupby(&#39;MAKE&#39;)[&#39;VEHICLE CLASS&#39;].describe()</pre><p>output:</p><pre>             count   unique                top       freq<br>    MAKE    <br>ACURA          247     7                  compact     102<br>ALFA ROMEO      42     3                 mid-size      18<br>ASTON MARTIN   106     4              minicompact      48<br>AUDI           805    15               subcompact     181<br>BENTLEY        118     8                 mid-size      45<br>BMW           1490    14               subcompact     428<br>BUGATTI         12     1               two-seater      12<br>BUICK          273     9                 mid-size     107<br>CADILLAC       434    11                 mid-size     160<br>CHEVROLET     2130    20  pickup truck - standard     395<br>CHRYSLER       425     7                full-size     141<br>DAEWOO          34     4                  compact      18<br>DODGE          925    14  pickup truck - standard     223<br>FERRARI         73     3               two-seater      47<br>FIAT            85     6              minicompact      52<br>FORD          1724    20  pickup truck - standard     356<br>GENESIS         42     4                full-size      25<br>GMC           1357    11  pickup truck - standard     350<br>HONDA          561    14                  compact     103<br>HUMMER          21     2                      suv      14<br>HYUNDAI        561    11                 mid-size     102<br>INFINITI       280    10                 mid-size      92<br>ISUZU           18     3                      suv      14<br>JAGUAR         364     9               two-seater      88<br>JEEP           544     7                      suv     201<br>KIA            532    11                 mid-size     108<br>LAMBORGHINI    111     2               two-seater     107<br>LAND ROVER     173     5                      suv      62<br>LEXUS          460    12                 mid-size     151<br>LINCOLN        225     9                 mid-size      68<br>MASERATI       125     6                full-size      37<br>MAZDA          602    11                  compact     137<br>MERCEDES-BENZ 1276    16                  compact     279<br>MINI           406     6              minicompact     135<br>MITSUBISHI     322     8                  compact      96<br>NISSAN         764    19                 mid-size     196<br>OLDSMOBILE      34     4                  compact      15<br>PLYMOUTH         2     2               subcompact       1<br>PONTIAC        253     8                  compact      67<br>PORSCHE        988     8              minicompact     534<br>RAM            153     4   pickup truck: standard      70<br>ROLLS-ROYCE    106     5                full-size      51<br>SAAB           190     7                  compact      43<br>SATURN         156     8                      suv      49<br>SCION           44     5                  compact      12<br>SMART           22     1               two-seater      22<br>SRT              4     1               two-seater       4<br>SUBARU         520    12                  compact     113<br>SUZUKI         199     7    station wagon - small      61<br>TOYOTA        1001    19                 mid-size     178<br>VOLKSWAGEN     701    14                  compact     315<br>VOLVO          515    12                  compact     177 </pre><p>look what amazing info we had:</p><p>count: number of example for each MAKE (company).</p><p>unique: how many unique values there are for each MAKE.</p><p>top: the most repeated value between the unique ones.</p><p>freq: how many times the top value has repeated.</p><p>There are 247 examples of <strong>ACURA, with 7 unique values of VEHICLE CLASS, the </strong>compact class was the top and has repeated 102 times.</p><h4>descending order of examples (rows) in data frame based on ENGINE SIZE:</h4><pre>df1=df.sort_values(&quot;ENGINE SIZE&quot;, axis=0, ascending=False)<br>df1</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swj_tBYYNwBRlo6m-m3zIw.png" /></figure><p>VIPER GTS COUPE model from SRT company has the biggest ENGINE SIZE.</p><h4>descending order of rows based on CYLINDERS:</h4><pre>df2=df.sort_values(&quot;CYLINDERS&quot;, axis=0, ascending=False)<br>df2</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7We8grTNEEbWbIlepAxCAQ.png" /></figure><h4>ascending order of rows based on EMISSIONS :</h4><pre>df.sort_values(&#39;EMISSIONS&#39;,ascending=True)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPtvx0JRJAvstgD2dzBiXQ.png" /></figure><p>INSIGHT model from HONDA have the lowest EMISSIONS value, while CHIRON SUPER SPORT and CHIRON PUR SPORT from BUGATTI have the highest one.</p><h4>query about specific type of FUEL:</h4><pre>df.query(&quot;FUEL==&#39;X&#39;&quot;)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMDeQHk_Jot4TtYstTcosQ.png" /></figure><h4>filtering some attributes based on specific type of FUEL:</h4><pre>df3=df.filter(items=[&#39;VEHICLE CLASS&#39;,&#39;MODEL&#39;,&#39;FUEL&#39;])<br>df3.query(&#39;FUEL==&quot;N&quot;&#39;)</pre><p>output:</p><pre>                  VEHICLE CLASS                          MODEL  FUEL<br>204                 van - cargo               RAM 2500 VAN NGV     N<br>863                 van - cargo               RAM 2500 VAN CNG     N<br>866             van - passenger             RAM 2500 WAGON CNG     N<br>872                   full-size             CROWN VICTORIA NGV     N<br>881                 van - cargo                   E250 VAN NGV     N<br>1435    pickup truck - standard        C2500 SILVERADO BI-FUEL     N<br>1436    pickup truck - standard            C2500 SILVERADO CNG     N<br>1446        subcompact CAVALIER                        BI-FUEL     N<br>1469    pickup truck - standard    K2500 SILVERADO 4X4 BI-FUEL     N<br>1470    pickup truck - standard        K2500 SILVERADO 4X4 CNG     N<br>1564                van - cargo               RAM 2500 VAN CNG     N<br>1567            van - passenger             RAM 2500 WAGON CNG     N<br>1577                  full-size             CROWN VICTORIA CNG     N<br>1611    pickup truck - standard                       F150 NGV     N<br>1651    pickup truck - standard           C2500 SIERRA BI-FUEL     N<br>1652    pickup truck - standard               C2500 SIERRA CNG     N<br>1678    pickup truck - standard       K2500 SIERRA 4X4 BI-FUEL     N<br>1679    pickup truck - standard           K2500 SIERRA 4X4 CNG     N<br>2193                van - cargo          EXPRESS CARGO BI-FUEL     N<br>2194                van - cargo              EXPRESS CARGO CNG     N<br>2302                van - cargo               RAM 2500 VAN CNG     N<br>2349    pickup truck - standard                       F150 NGV     N<br>2434                van - cargo           SAVANA CARGO BI-FUEL     N<br>2435                van - cargo               SAVANA CARGO CNG     N<br>3039                    compact                AVALIER BI-FUEL     N<br>3049                van - cargo          EXPRESS CARGO BI-FUEL     N<br>3050                van - cargo              EXPRESS CARGO CNG     N<br>3194    pickup truck - standard               F150 4X4 BI-FUEL     N<br>3196    pickup truck - standard                   F150 BI-FUEL     N<br>3198    pickup truck - standard                       F150 NGV     N<br>3299                van - cargo           SAVANA CARGO BI-FUEL     N<br>3300                van - cargo               SAVANA CARGO CNG     N<br>15621                  mid-size               IMPALA DUAL FUEL     N</pre><p>VEHICLE CLASS: van — cargo, van — passenger, full-size, pickup truck — standard, subcompact, compact, mid-size consume FUEL from type N.</p><h4>checking the max and min value for FUEL CONSUMPTION:</h4><pre>print(df[&#39;FUEL CONSUMPTION&#39;].max())<br>print(df[&#39;FUEL CONSUMPTION&#39;].min())</pre><p>output:</p><pre>30.6<br> 3.5</pre><h4>finding the location of max value for FUEL CONSUMPTION:</h4><pre>df.loc[(df[&#39;FUEL CONSUMPTION&#39;]==30.6)]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HdLJvTkHEVO_z6D8TcfMQ.png" /></figure><p>ENZO from FERRARI, EXPRESS 3500 PASSENGER FFV from CHEVROLET, and SAVANA 3500 PASSENGER FFV from GMC are the most fuel consuming .</p><h4>finding the location of min value for FUEL CONSUMPTION:</h4><pre>df.loc[(df[&#39;FUEL CONSUMPTION&#39;]==3.5)]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oLFSbS75TwejuIZyCBamg.png" /></figure><p>PRIUS C from TOYOTA is the least fuel consuming</p><p>note: you can use another way to query about min value like the following:</p><pre>df.loc[(df[&#39;FUEL CONSUMPTION&#39;]==df[&#39;FUEL CONSUMPTION&#39;].min())]</pre><h4>aggregating HWY (L/100 km) based on mean, max, min:</h4><pre>df.agg({&#39;HWY (L/100 km)&#39;:[&#39;mean&#39;,&#39;max&#39;,&#39;min&#39;]})</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*tykQfih2SDezhsovdT7FEg.png" /></figure><h4>querying about min value of HWY (L/100 km):</h4><pre>df[df[&#39;HWY (L/100 km)&#39;]==3.200000]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkZy_Ogh-PTrqAXnfinvEw.png" /></figure><p>INSIGHT model from HONDA company has the lowest value of HWY (L/100 km), also the TRANSMISSION is M5 , FUEL type is X, the FUEL CONSUMPTIN is close to the min value of consumption which is 3.5 (we query about it previously).</p><h4>aggregating COMB (L/100 km) based on mean, max, min:</h4><pre>df.agg({&#39;COMB (L/100 km)&#39;:[&#39;mean&#39;,&#39;max&#39;,&#39;min&#39;]})</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*lHZJn2g5PPRBdF_KEkTjHQ.png" /></figure><h4>querying about min value of COMB (L/100 km):</h4><pre>df[df[&#39;COMB (L/100 km)&#39;]==3.600000]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnDnO3Kgew5COovGcr9tbA.png" /></figure><p>again INSIGHT model car from HONDA has the lowest value for COMB (L/100 km), the FUEL type is X , TRANSMISSION is M5,the FUEL consumption is close to min value (3.5).</p><p>hint: positive correlation between COMB (L/100 km) and HWY (L/100 km) because decreasing the value of one of them leads to decrease value of the other, you can verify by query bout the max value of those two attributes.</p><h4>n largest values for COMB (mpg):</h4><pre>df.nlargest(20,columns=&#39;COMB (mpg)&#39;)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIFO-AhtGlHPfQgfIdnxSA.png" /></figure><p>INSIGHT model from HONDA has the highest COMB (mpg) value , previously we found that INSIGHT model from HONDA has the lowest value for both HWY (L/100 km) and COMB (L/100 km), and this an index of negative correlation between HWY (L/100 km) and COMB (mpg) ,COMB (L/100 km) and COMB (mpg).</p><h4>n smallest values for COMB (mpg):</h4><pre>df.nsmallest(20,columns=&#39;COMB (mpg)&#39;)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rgg2jFZDw_81cTLFlRL6Zg.png" /></figure><p>FERRARI with ENZO model has the lowest value of COMB (mpg).</p><p>note: you should looking at both make and model when query about data, as we see here not all FERRARI cars have the lowest value of COMB (mpg) just ENZO model.</p><h4>sorting value of one column based on the value of the other:</h4><p>maybe you want to sort KIA cars based on ENGINE SIZE:</p><pre>df[df[&#39;MAKE&#39;]==&#39;KIA&#39;].sort_values(&#39;ENGINE SIZE&#39;,ascending=True)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NM4ITivYE0ZNI6QDPD3JZA.png" /></figure><p>RIO model’s engine size is the smallest , while K900 is the biggest one.</p><h4>multiple condition:</h4><pre>df[(df.MAKE==&#39;LEXUS&#39;)&amp; (df[&#39;VEHICLE CLASS&#39;] ==&#39;compact&#39;)]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrKUVll8psMLbsXb9Qfh2g.png" /></figure><h4>multiple condition:</h4><pre>df[(df.MAKE==&#39;ROLLS-ROYCE&#39;)&amp; (df[&#39;FUEL CONSUMPTION&#39;]&lt;10.0)]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFvrwncFvwcLAdQXlh7QmQ.png" /></figure><p>empty data frame, let’s discover why?</p><h4>statistical description of multiple condition:</h4><pre>df.loc[df.MAKE==&#39;ROLLS-ROYCE&#39;,&#39;FUEL CONSUMPTION&#39;].describe()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*DEsMKJ_uvvBa-Rh4ZWzjGA.png" /></figure><p>the min value of FUEL CONSUMPTION for this condition is 16.2 that is the reason of empty data frame in the previous query.</p><h4>multiple condition:</h4><pre>df[(df.MAKE==&#39;FERRARI&#39;)&amp;(df.FUEL==&#39;Z&#39;)]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nnxKJUPTEQfgKw30SC_Xw.png" /></figure><h4>groupby (count and order on a column):</h4><pre>df.groupby([&#39;MAKE&#39;,&#39;CYLINDERS&#39;]).size().to_frame(&#39;count&#39;).reset_index().sort_values(&#39;CYLINDERS&#39;,ascending=True)</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*GOUu30EBYxwRQA93-9llqA.png" /></figure><p>there are 16 examples of MAZDA car with number of cylinders =2, pay your attention this value isn’t the same of all MAZDA cars. you can check that by the following :</p><pre>df.loc[(df[&#39;MAKE&#39;]==&#39;MAZDA&#39;),&#39;CYLINDERS&#39;].unique()</pre><p>output:</p><pre>array([4, 6, 2])</pre><h4>querying about column’s value present is specific list:</h4><pre>df[df[&#39;EMISSIONS&#39;].isin([200,250,300])]</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-ytxR9OAquvTS91eqrzgA.png" /></figure><h4>exploring correlation between numerical attributes:</h4><pre>df_correlation=df.corr(numeric_only = True)<br>df_correlation</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeTXaMoNU3OFcSyc3KnkYw.png" /></figure><p>in general there are 4 types of correlation:</p><p>positive : one variable increases as the other increases (weak from 0.1 to 0.3, moderate from 0.3 to 0.5, and strong from 0.5 to 1.0)</p><p>negative: one variable increases as the other decreases (Weak from -0.1 to -0.3, moderate from -0.3 to -0.5, and strong from -0.5 to -1.0)</p><p>perfect: each variable related with itself by perfect correlation.</p><p>no correlation: no relationship between the variables.</p><p>the table below contains the correlation type between the attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*catCCd_pKkCzay_ehOrPKA.png" /></figure><p>In this story we discussed pandas library which is powerful tool with various methods to analyze data like identify types, missing values, and get statistical description, then study the relationship between the attributes to understand the whole picture of the data.</p><p>Enjoy reading, and don&#39;t hesitate to share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6f1b9951f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization: Go Beyond The Numbers, Get Insights From Your Data]]></title>
            <link>https://medium.com/@engulayousef99/data-visualization-go-beyond-the-numbers-get-insights-from-your-data-a35efd95d0bc?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35efd95d0bc</guid>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 16:03:59 GMT</pubDate>
            <atom:updated>2025-03-01T21:45:03.358Z</atom:updated>
            <content:encoded><![CDATA[<p>Am I the only one who hate looking at numbers or there are someone else?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*iIZQonLQysrKYuR6.jpg" /><figcaption>image from Pixabay</figcaption></figure><p>I always wonder what life would be like for someone who works in data field if he has to spend his time holding his gaze into tables.</p><h4>What will happen :</h4><blockquote>if he has a meeting with clients and he wanted to show them his data analysis summary in an impressive way ….?</blockquote><blockquote>if he want to run some statistical tests and he run out of finger and toes to count on….?</blockquote><p>I am not a wise but trust me data without a visualization will be so boring, if you agree, then this story is for you.</p><h3><strong>What is data Visualization?</strong></h3><p><strong>Data Visualization: it is a Graphical representation of information and data using charts, graphs, maps, it is a part of EDA (Exploratory Data Analysis) phase, visualization is more than a colorful plots because it has many uses in data science and data analysis field, for include not exclusive:</strong></p><p>1_ Analyze data and recognize patterns and relation between them.</p><p>2_ Tool for data preprocessing like detecting outliers in features.</p><p>3_ Tell stories a bout your data.</p><p>Let’s start by the explanation of analyze data:</p><p>analysis is the transformation and organization of data in order to draw conclusions, make predictions and informed decision making.</p><p>There are 3 types of analysis you can do with data visualization:</p><p>Univariate analysis: analyze one variable to understand pattern, we do not look for causes or relation, an instance for this analysis count plot and distribution plot.</p><p>Bivariate analysis: analyze two variables to understand the relation between them, e.g. box plot, bar plot, and scatter plot.</p><p>Multiple analysis: analyze more than two variables, e.g. heatmap, pair plot.</p><p>Moving to data preprocessing: it is a critical step in any machine learning project, it aims to make sure that your data is completely clean from any extreme points as outlier, noise, and missing values.</p><p>Thanks for God, python programming language equip us with Seaborn library, you have so many options in it such as box plot, scatter plot, heatmap, and histogram to identify value differs from the rest or the absent ones .</p><p>Now to move from theory to practice we will jump to Google Colab and apply all what we learned .</p><h4>First we will install some libraries:</h4><pre>!pip install numpy <br>!pip install pandas<br>!pip install seaborn <br>!pip install matplotlib</pre><p>if you have installed before you will get the following output:</p><pre>Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (1.26.4)<br>Requirement already satisfied: pandas in /usr/local/lib/python3.11/dist-packages (2.2.2)<br>Requirement already satisfied: numpy&gt;=1.23.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (1.26.4)<br>Requirement already satisfied: python-dateutil&gt;=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (2.8.2)<br>Requirement already satisfied: pytz&gt;=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas) (2024.2)<br>Requirement already satisfied: tzdata&gt;=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas) (2025.1)<br>Requirement already satisfied: six&gt;=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil&gt;=2.8.2-&gt;pandas) (1.17.0)<br>Requirement already satisfied: seaborn in /usr/local/lib/python3.11/dist-packages (0.13.2)<br>Requirement already satisfied: numpy!=1.24.0,&gt;=1.20 in /usr/local/lib/python3.11/dist-packages (from seaborn) (1.26.4)<br>Requirement already satisfied: pandas&gt;=1.2 in /usr/local/lib/python3.11/dist-packages (from seaborn) (2.2.2)<br>Requirement already satisfied: matplotlib!=3.6.1,&gt;=3.4 in /usr/local/lib/python3.11/dist-packages (from seaborn) (3.10.0)<br>Requirement already satisfied: contourpy&gt;=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (1.3.1)<br>Requirement already satisfied: cycler&gt;=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (0.12.1)<br>Requirement already satisfied: fonttools&gt;=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (4.55.7)<br>Requirement already satisfied: kiwisolver&gt;=1.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (1.4.8)<br>Requirement already satisfied: packaging&gt;=20.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (24.2)<br>Requirement already satisfied: pillow&gt;=8 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (11.1.0)<br>Requirement already satisfied: pyparsing&gt;=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (3.2.1)<br>Requirement already satisfied: python-dateutil&gt;=2.7 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (2.8.2)<br>Requirement already satisfied: pytz&gt;=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas&gt;=1.2-&gt;seaborn) (2024.2)<br>Requirement already satisfied: tzdata&gt;=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas&gt;=1.2-&gt;seaborn) (2025.1)<br>Requirement already satisfied: six&gt;=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil&gt;=2.7-&gt;matplotlib!=3.6.1,&gt;=3.4-&gt;seaborn) (1.17.0)<br>Requirement already satisfied: matplotlib in /usr/local/lib/python3.11/dist-packages (3.10.0)<br>Requirement already satisfied: contourpy&gt;=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.3.1)<br>Requirement already satisfied: cycler&gt;=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (0.12.1)<br>Requirement already satisfied: fonttools&gt;=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (4.55.7)<br>Requirement already satisfied: kiwisolver&gt;=1.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.4.8)<br>Requirement already satisfied: numpy&gt;=1.23 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.26.4)<br>Requirement already satisfied: packaging&gt;=20.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (24.2)<br>Requirement already satisfied: pillow&gt;=8 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (11.1.0)<br>Requirement already satisfied: pyparsing&gt;=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (3.2.1)<br>Requirement already satisfied: python-dateutil&gt;=2.7 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (2.8.2)<br>Requirement already satisfied: six&gt;=1.5 in /usr/local/lib/python3.11/dist-packages (from python-dateutil&gt;=2.7-&gt;matplotlib) (1.17.0)</pre><h4>import the previous libraries in the notebook:</h4><pre>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><p>The dataset used in this story is Forest Fire data, you can download it from UCI Machine Learning Repository.</p><p>The link of Forest Fire Data: <a href="https://archive.ics.uci.edu/ml/datasets/forest+fires">https://archive.ics.uci.edu/ml/datasets/forest+fires</a></p><p>The link of download it:</p><p><a href="https://archive.ics.uci.edu/static/public/162/forest+fires.zip">https://archive.ics.uci.edu/static/public/162/forest+fires.zip</a>.</p><h4>reading the dataset:</h4><pre>df=pd.read_csv(&#39;/content/forestfires.csv&#39;)<br>df</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*cjTDxWK_1ab4CNyRpG_hIg.png" /></figure><p>But what do each of this attributes mean?</p><p><em>X: x-axis spatial coordinate within the Montesinho park map: 1 to 9.</em></p><p><em>Y: y-axis spatial coordinate within the Montesinho park map: 2 to 9.</em></p><p><em>FFMC: The Fine Fuel Moisture Code( index from the FWI system: 18.7 to 96.20) is a numeric rating of the moisture content of litter and other cured fine fuels. This code is an indicator of the relative ease of ignition and the flammability of fine fuel.</em></p><p><em>DMC: The Duff Moisture Code (index from the FWI system: 1.1 to 291.3) is a numeric rating of the average moisture content of loosely compacted organic layers of moderate depth. This code gives an indication of fuel consumption in moderate duff layers and medium-size woody material.</em></p><p><em>DC: The Drought Code (index from the FWI system: 7.9 to 860.6) is a numeric rating of the average moisture content of deep, compact organic layers. This code is a useful indicator of seasonal drought effects on forest fuels and the amount of smoldering in deep duff layers and large logs.</em></p><p><em>ISI: The Initial Spread Index (index from the FWI system: 0.0 to 56.10) is a numeric rating of the expected rate of fire spread. It is based on wind speed and FFMC. Like the rest of the FWI system components, ISI does not take fuel type into account. Actual spread rates vary between fuel types at the same IS.</em></p><p><em>Temp: temperature: 2.2 to 33.30.</em></p><p><em>RH: relative humidity: 15.0 to 100.</em></p><p><em>area: (target column)the burned area of the forest: 0.00 to 1090.84</em></p><h4>Generating the summary of the Data Frame, this will include info about columns with their names, their data types, and missing values.</h4><pre>df.info()</pre><p>output:</p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 517 entries, 0 to 516<br>Data columns (total 13 columns):<br> #   Column  Non-Null Count  Dtype  <br>---  ------  --------------  -----  <br> 0   X       517 non-null    int64  <br> 1   Y       517 non-null    int64  <br> 2   month   517 non-null    object <br> 3   day     517 non-null    object <br> 4   FFMC    517 non-null    float64<br> 5   DMC     517 non-null    float64<br> 6   DC      517 non-null    float64<br> 7   ISI     517 non-null    float64<br> 8   temp    517 non-null    float64<br> 9   RH      517 non-null    int64  <br> 10  wind    517 non-null    float64<br> 11  rain    517 non-null    float64<br> 12  area    517 non-null    float64<br>dtypes: float64(8), int64(3), object(2)<br>memory usage: 52.6+ KB</pre><h4>Change type from object to string for facilitate data visualization process:</h4><pre>df[[&#39;month&#39;,&#39;day&#39;]] = df[[&#39;month&#39;,&#39;day&#39;]].astype(&#39;string&#39;)</pre><p>Since the target in our dataset is area column we will create categorical one called area_classifaction, the value of it will be as the following:</p><p>non_burned if area value = zero</p><p>burnd if area value != zero</p><p>this column will help us at analyze the attributes with target</p><pre>df[&#39;area_classifaction&#39;] = np.where(df[&#39;area&#39;] == 0.0, &quot;non_burned&quot;, &quot;burned&quot;)<br>df[&#39;area_classifaction&#39;]</pre><p>output:</p><pre>area_classifaction<br>0 non_burned<br>1 non_burned<br>2 non_burned<br>3 non_burned<br>4 non_burned<br>... ...<br>512 burned<br>513 burned<br>514 burned<br>515 non_burned<br>516 non_burned<br>517 rows × 1 columns</pre><h4>check duplicated values:</h4><pre>df.duplicated().sum()</pre><p>output:</p><pre>4</pre><h4>getting rid of duplicated values:</h4><pre>df = df.drop_duplicates()<br>df.duplicated().values.any()</pre><p>output:</p><pre>False</pre><h4>using heatmap to detect missing data:</h4><pre>plt.figure(figsize=(10,8))<br>plt.xticks(rotation = 60)<br>sns.heatmap(df.isnull(),cbar=False,cmap=&#39;viridis&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*X9eCP-QuteYRiRvzKmUa1Q.png" /></figure><p>looking at the previous plot we see:</p><p>no empty spaces in the color for each attributes → no missing values</p><p>we can use another way to make sure that results are accurate:</p><pre>df.isnull().sum()</pre><p>output:</p><pre><br>0<br>X 0<br>Y 0<br>month 0<br>day 0<br>FFMC 0<br>DMC 0<br>DC 0<br>ISI 0<br>temp 0<br>RH 0<br>wind 0<br>rain 0<br>area 0<br>area_classifaction 0</pre><h4>detect outliers using boxplot:</h4><pre>sns.set(style=&quot;ticks&quot;, palette=&quot;inferno&quot;)<br>f, axes = plt.subplots(5, 2, sharey=False, figsize=(8, 8))<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;X&quot;],ax = axes[0,0])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;Y&quot;],ax=axes[0,1])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;FFMC&quot;],ax=axes[1,0])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;DMC&quot;],ax=axes[1,1])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;DC&quot;],ax=axes[2,0])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;ISI&quot;],ax=axes[2,1])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;temp&quot;],ax=axes[3,0])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;RH&quot;],ax=axes[3,1])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;wind&quot;],ax=axes[4,0])<br>sns.boxplot(x=df[&quot;area_classifaction&quot;], y=df[&quot;rain&quot;],ax=axes[4,1])<br>#f.suptitle(&quot;Boxplot of the fatcors by  burned area&quot;)<br>plt.tight_layout()<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*liVileD4A8Ve6g7J8PvwFQ.png" /></figure><p>before we interpret the output we will just take a quick look about the boxplot explanation, boxplot sometimes known as the box &amp; whisker plot, it shows the distribution of the quantitative data that represents the comparisons between variables, the box shows the quartiles of the dataset while the whisker extend to show the rest of the distribution, the dots outside the whisker indicate the presence of outliers.</p><p>now based on the previous definition, except of X column all attributes have outliers some of them are just in burned area and some are in both burned and non_burned area, we will use quantile_based Flooring and Capping technique for cleansing.</p><pre>def flooring_capping(df):<br>  lower=df.quantile(0.10)<br>  upper=df.quantile(0.90)<br>  df= np.where(df&lt;lower,lower,df)<br>  df=np.where(df&gt;upper,upper,df)<br>  return df</pre><p>In this technique, we will do the flooring (e.g., the 10th percentile) for the lower values and capping (e.g., the 90th percentile) for the higher values then replace each point less than the flooring with flooring and each point more than the capping with capping, i also used df.loc to apply this method in more specific way because outlier value in burned area isn’t the same in non_buned area for any attribute.</p><pre>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;wind&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;wind&#39;])<br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;DC&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;DC&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;Y&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;Y&#39;])<br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;Y&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;Y&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;FFMC&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;FFMC&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;FFMC&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;FFMC&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;DMC&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;DMC&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;DMC&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;DMC&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;temp&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;temp&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;ISI&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;ISI&#39;])<br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;ISI&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;ISI&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;RH&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;RH&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;])</pre><p>when i run the previous code, i got the following error</p><pre>&lt;ipython-input-7-8d6eb0e71d9f&gt;:21: FutureWarning: Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas. Value &#39;[51.  33.  33.  72.7 72.7 29.  27.  72.7 63.  40.  51.  38.  72.  42.<br> 25.3 44.  27.  47.  35.  44.  40.  38.  44.  43.  32.  60.  34.  48.<br> 25.3 39.  25.3 72.7 37.  39.  32.  62.  25.3 60.  27.  43.  37.  42.<br> 54.  48.  72.7 25.3 70.  36.  35.  46.  25.3 34.  42.  45.  25.3 63.<br> 50.  40.  51.  39.  59.  35.  33.  31.  44.  37.  33.  33.  26.  27.<br> 37.  25.3 43.  30.  72.7 43.  72.  66.  25.3 39.  44.  51.  47.  45.<br> 25.3 27.  34.  36.  25.3 59.  25.3 32.  43.  25.3 64.  48.  25.3 72.7<br> 39.  66.  40.  29.  72.7 52.  29.  33.  45.  56.  43.  25.3 39.  35.<br> 27.  27.  30.  27.  30.  36.  72.7 43.  42.  45.  50.  25.3 49.  43.<br> 46.  35.  40.  39.  46.  42.  38.  52.  58.  66.  72.7 51.  25.3 72.7<br> 28.  46.  59.  25.3 32.  51.  40.  72.7 49.  32.  30.  53.  48.  45.<br> 43.  72.7 25.3 38.  72.7 52.  45.  27.  27.  72.7 27.  30.  25.3 27.<br> 27.  27.  32.  35.  51.  72.7 44.  51.  37.  72.7 57.  55.  39.  27.<br> 72.7 58.  72.7 42.  54.  51.  72.7 48.  34.  25.3 68.  32.  34.  36.<br> 41.  27.  46.  31.  42.  33.  50.  25.3 25.3 56.  56.  34.  45.  38.<br> 45.  51.  72.7 58.  72.7 72.7 70.  35.  72.7 61.  65.  54.  56.  48.<br> 59.  64.  64.  27.  25.3 27.  58.  33.  25.3 27.  42.  65.  65.  69.<br> 72.7 41.  41.  35.  42.  31. ]&#39; has dtype incompatible with int64, please explicitly cast to a compatible dtype first.<br>  df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;])</pre><p>you can fix it by changing the type of RH column to float 64</p><pre>df[&#39;RH&#39;] = df[&#39;RH&#39;].astype(&#39;float64&#39;)</pre><p>then run flooring_capping method for RH again:</p><pre>df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;RH&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;burned&#39;,&#39;RH&#39;])<br><br>df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;]=flooring_capping(df.loc[df[&#39;area_classifaction&#39;]==&#39;non_burned&#39;,&#39;RH&#39;])</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*w_rh9iwz2Dn4GlwrxhIHyA.png" /></figure><p>almost of outliers have been removed, still a little you can removed using another technique like trimming.</p><h4>univariate analysis: countplot for categorical data:</h4><pre>plt.figure(figsize=(10,8))<br>sns.countplot(x=&#39;month&#39;,data=df,palette=&#39;husl&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*ETmXzKhNGmx5_ughran-mA.png" /></figure><p>august month has the highest number of occurrence, which tell us that most fires broke out in it.</p><h4>univariate analysis: histogram for each attribute:</h4><pre>fig, axes = plt.subplots(nrows=5, ncols=3, figsize=(15, 10))<br><br># Flatten the axes array (makes it easier to iterate over)<br>axes = axes.flatten()<br><br># Loop through each column and plot a histogram<br>for i, column in enumerate(df.columns):<br><br>    # Add the histogram<br>    df[column].hist(ax=axes[i], # Define on which ax we&#39;re working on<br>                    edgecolor=&#39;white&#39;, # Color of the border<br>                    color=&#39;#69b3a2&#39;,<br>                    # Color of the bins<br>                   )<br><br>    # Add title and axis label<br>    axes[i].set_title(f&#39;{column} distribution&#39;)<br>    axes[i].set_xlabel(column)<br>    axes[i].set_ylabel(&#39;Frequency&#39;)<br>    axes[13].set_axis_off()<br>    axes[14].set_axis_off()<br><br><br># Adjust layout<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OP6OToOSIQRvXFoUhTLULg.png" /></figure><p>area_classification has the Bernoulli distribution.</p><p>only temp column has the Normal distribution.</p><h4>Bivariate analysis: scatterplot for some attributes:</h4><pre>sns.scatterplot(data=df, x=&quot;temp&quot;, y=&quot;area&quot;,color=&#39;red&#39;,hue=&#39;area_classifaction&#39;,palette=&#39;inferno&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*XOGjgoFK73HYLdKFEWkgAA.png" /></figure><p>the scatter plot indicates when the temp is more than 20 and less than 30 the burned area will be larger.</p><pre>sns.scatterplot(data=df, x=&quot;wind&quot;, y=&quot;area&quot;,palette=&#39;husl&#39;,hue=&#39;area_classifaction&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*RZdgZXhPBi4ul0RCK9Mkow.png" /></figure><p>the largest amount of burned area has recorded when the wind speed is between 4 and 5.</p><pre>sns.scatterplot(data=df, x=&quot;RH&quot;, y=&quot;area&quot;,hue=&#39;area_classifaction&#39;,palette=&#39;pastel&#39;)<br>plt.show()</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*3NDgseIeGz8UHQPOpYFwBQ.png" /></figure><p>the burned area were largest when the RH ratio is less than 30.</p><h4>Multivariate analysis: heatmap</h4><p>first: drop categorical attributes from dataframe</p><pre>df1=df.drop(columns=[&#39;month&#39;,&#39;day&#39;,&#39;area_classifaction&#39;])<br>df1</pre><p>choosing the method you want to plot heatmap between the variables based on it, here I used corr() method.</p><pre>df1=df1.corr()<br>df1</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*4tAPa3VE692R0BXI_1TNKA.png" /></figure><h4>heatmap:</h4><pre>plt.figure(figsize=(12,8))<br>sns.heatmap(df1,annot=True,linecolor=&#39;black&#39;,linewidths=0.2,cmap=&#39;BrBG&#39;,cbar=True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*TCjK8gyqOkp6bfOM088dfA.png" /></figure><p>insights from heatmap:</p><p>positive correlation between X,Y.</p><p>strong positive correlation between FFMC and ISI.</p><p>positive correlation between FFMC and temp ,FFMC and DMC,FFMC and DC.</p><p>negative correlation between FFMC and RH.</p><p>positive correlation DMC and temp, DMC and ISI,</p><p>strong positive correlation between DMC and DC</p><p>negative correlation between DC and wind</p><p>positive correlation between DC and temp.</p><p>positive correlation ISI and temp.</p><p>negative correlation between temp and RH</p><p>negative correlation between RH and ISI.</p><p>negative correlation between wind and temp.</p><h4>descending sorting of attributes by their correlation with area</h4><pre>plt.figure(figsize=(8, 12))<br>heatmap = sns.heatmap(df1.corr()[[&#39;area&#39;]].sort_values(by=&#39;area&#39;, ascending=False), vmin=-1, vmax=1, annot=True, cmap=&#39;BrBG&#39;)<br>heatmap.set_title(&#39;Features Correlating with burned area&#39;, fontdict={&#39;fontsize&#39;:18}, pad=16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*SOtX9sdQfxeKP1INzUoeRQ.png" /></figure><p>negative correlation between area and rain.</p><p>negative correlation between area and RH.</p><p>negative correlation between area and ISI.</p><p>negative correlation between area and DMC.</p><p>negative correlation between area and wind.</p><p>the negative correlation means when one variable increases the other one decreases.</p><p>Finally i hope this story could spot the light on the importance of data visualization and it’s use cases from exploring the data, processing it to taking hints and recognizing patterns.</p><p>Enjoy reading and don’t hesitate to share your thoughts and feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35efd95d0bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to understand machine learning world even if you weren’t an AI engineer]]></title>
            <link>https://medium.com/@engulayousef99/how-to-understand-machine-learning-world-even-if-you-werent-an-ai-engineer-c86962757cb2?source=rss-6874d89de1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86962757cb2</guid>
            <dc:creator><![CDATA[Ula Yousef]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 23:10:42 GMT</pubDate>
            <atom:updated>2025-01-11T23:10:42.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vo22yxkB51MXKx9n.jpg" /><figcaption>image from Pixabay</figcaption></figure><p>It seems that everyone today has heard of Machine Learning especially that Artificial Intelligence uses have become more popular day after day, when you open your phone, read a post on Facebook, watch a video on YouTube, or using ChatGPT and so on.</p><p>If you need to get an idea about Machine Learning this story will be a good choice for you.</p><p>Let’s start by defining Artificial Intelligence and the relation of Machine Learning to it:</p><p><strong><em>Artificial Intelligence (AI)</em></strong>: is a field of computer science which concerns with enabling computers and machines to perform the tasks that require human intelligence like: understanding language, speech recognition, decision making, image recognition,……etc.</p><p><strong><em>Machine Learning (ML)</em> </strong>: is a part of AI field which focuses on enabling computers to learn automatically from data then make prediction without being programmed to do that.</p><p>But what does that mean? you can find the answer in this two cases:</p><blockquote>First case:</blockquote><p>A person who don’t know any thing about life, his parents taught him how to do his tasks, he just takes the orders and performs it without understanding.</p><blockquote>Second case:</blockquote><p>A person who tries to perform his tasks alone, at first he makes some mistakes, but he learns from it, trying to avoid it</p><p>Now let’s ask our selves what will happen when those two people get a new different tasks?</p><p>in the first case, the one was taking orders, when he encountered a problem he can’t solve it alone, and even if he tries he will do like what parents had told him, so if they taught him something wrong he will do his tasks in a wrong way , right? do you know why? because he was learning a process without understanding of how it is going on, in one word he has been programmed to do his task like when you see this do that, if x is happened then do Y (monkey see monkey do )and this the definition of programming.</p><p>moving to the second case we see the following process:</p><p>no pre-orders →dive deep into the core of the problem →understand the relation between variables →solve the problem successfully and gain knowledge about the given subject.</p><p>the second case is the definition of machine learning.</p><p>There are 3 types of machine learning algorithms:</p><p><strong>1_ Supervised Learning</strong>: in this type of learning there is a labeled data used at model training to predict outcomes and recognize patterns, (learn the relationship between the inputs and the output then predict the future outputs based on what the model has learned)</p><p>For example: someone works in an estate agency for selling houses, at the beginning of his career he was confused about determining the actually price of houses, but after a period of training he could distinguish the house’s price which is related with many factors like: size of house, number of rooms, location, proximity to workplaces, schools, shopping facilities and public transport, after this find he could predict the price of any house based on its features even if the owner didn’t tell him the cost.</p><p>2_<strong> Unsupervised Machine Learning</strong> : there is no labeled data and the purpose is trying to gather the data based on the similarity between them.</p><p>For example: a man works in market suffering from chaos ,he decided to arrange the goods according to similarities and differences between them based on the features of each commodity, meat in a counter, fruits in another one, detergents in counter,….,etc.</p><p><strong>3_ Reinforcement Learning</strong> : in this type of learning the machine learning algorithms perform the task by interacting with an environment to maximize cumulative rewards and learning from the mistakes they have done, there are 3 main parts of this type :</p><p>a_ Agent: the one which learn and make a decision.</p><p>b_ Environment: involves everything the agent interact with.</p><p>c_ Actions : what the agent can do.</p><p>an instance of this type is when you are playing a chess with your computer ,in chess, the environment is the board, the actions are the moves, and the rewards are determined by the game outcome — win, loss, or draw.</p><p>To make sure you start on the right foot on ML world just replace the following word in the story like this:</p><p>person with model.</p><p>problem with new data.</p><p>Finally I hope this article give you a hint about machine learning in a simple way, and be a straightforward guide for you in this field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86962757cb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>