<?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 Nirav Mehta on Medium]]></title>
        <description><![CDATA[Stories by Nirav Mehta on Medium]]></description>
        <link>https://medium.com/@nmehta1004?source=rss-2c20a754a54e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6Vf6mmk4qBXWxc53.jpg</url>
            <title>Stories by Nirav Mehta on Medium</title>
            <link>https://medium.com/@nmehta1004?source=rss-2c20a754a54e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:36:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nmehta1004/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[Pandas for Data Science — Data Cleaning Part 1]]></title>
            <link>https://medium.com/@nmehta1004/pandas-for-data-science-data-cleaning-part-1-18029f8f0436?source=rss-2c20a754a54e------2</link>
            <guid isPermaLink="false">https://medium.com/p/18029f8f0436</guid>
            <dc:creator><![CDATA[Nirav Mehta]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 16:08:42 GMT</pubDate>
            <atom:updated>2024-08-18T16:09:54.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92eZZ3CUvFJ27CcofW5thg.png" /></figure><p><strong>Data cleaning</strong> in Pandas involves the process of preparing and correcting raw data to ensure it is accurate, consistent, and ready for analysis. This typically includes handling missing values, correcting data types, removing duplicates, fixing inconsistencies, and dealing with outliers. The goal is to transform messy data into a format that is usable and reliable for further processing or analysis.</p><p>Key data cleaning tasks in Pandas include:</p><ul><li><strong>Handling Missing Data:</strong> Using functions like dropna() to remove rows/columns with missing values or fillna() to replace them with a specified value.</li><li><strong>Removing Duplicates:</strong> Using drop_duplicates() to eliminate duplicate rows.</li><li><strong>Correcting Data Types:</strong> Converting columns to the appropriate data type with astype().</li><li><strong>String Manipulation:</strong> Cleaning text data using string methods like str.strip(), str.lower(), etc.</li><li><strong>Replacing Values:</strong> Using replace() to correct or update specific values.</li></ul><p>These steps ensure that the data is in a clean, consistent state, making it easier to analyze and draw accurate conclusions.</p><blockquote>dropna() — You can remove rows or columns with missing values using dropna().</blockquote><pre>DataFrame.dropna(axis=0, how=&#39;any&#39;, thresh=None, subset=None, inplace=False)</pre><pre>import pandas as pd<br><br># Sample DataFrame with missing values<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Age&#39;: [24, 27, None, 22, None],<br>    &#39;City&#39;: [&#39;New York&#39;, None, &#39;San Francisco&#39;, &#39;Los Angeles&#39;, &#39;Chicago&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br>print(&quot;--------------------------------------------------&quot;)<br># Drop rows with missing values<br>df_cleaned = df.dropna()<br><br># Display the cleaned DataFrame<br>print(&quot;\nDataFrame after dropna():&quot;)<br>print(df_cleaned)</pre><pre>Original DataFrame:<br>      Name   Age           City<br>0    Alice  24.0       New York<br>1      Bob  27.0           None<br>2  Charlie   NaN  San Francisco<br>3    David  22.0    Los Angeles<br>4   Edward   NaN        Chicago<br>--------------------------------------------------<br><br>DataFrame after dropna():<br>    Name   Age         City<br>0  Alice  24.0     New York<br>3  David  22.0  Los Angeles</pre><p>You can also customize the behavior of dropna() by using various parameters, such as how, axis, and thresh.</p><pre>import pandas as pd<br><br># Sample DataFrame with missing values<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Age&#39;: [24, 27, None, 22, None],<br>    &#39;City&#39;: [&#39;New York&#39;, None, &#39;San Francisco&#39;, &#39;Los Angeles&#39;, &#39;Chicago&#39;],<br>    &#39;Score&#39;: [85, None, 88, None, 90]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br>print(&quot;--------------------------------------------------&quot;)<br><br># Drop rows where all elements are NaN (how=&#39;all&#39;)<br>df_drop_all = df.dropna(how=&#39;all&#39;)<br><br># Drop rows where any element is NaN (how=&#39;any&#39;)<br>df_drop_any = df.dropna(how=&#39;any&#39;)<br><br># Drop columns where all elements are NaN (axis=1, how=&#39;all&#39;)<br>df_drop_col_all = df.dropna(axis=1, how=&#39;all&#39;)<br><br># Drop rows that have less than 3 non-NaN values (thresh=3)<br>df_drop_thresh = df.dropna(thresh=3)<br><br># Drop rows where &#39;Age&#39; or &#39;City&#39; has missing values<br>df_subset = df.dropna(subset=[&#39;Age&#39;, &#39;City&#39;])<br><br># Drop rows with any missing values and modify the DataFrame in place<br>df.dropna(inplace=True)<br><br># Display the DataFrames after applying dropna() with different parameters<br>print(&quot;\nDataFrame after dropna(how=&#39;all&#39;):&quot;)<br>print(df_drop_all)<br>print(&quot;--------------------------------------------------&quot;)<br>print(&quot;\nDataFrame after dropna(how=&#39;any&#39;):&quot;)<br>print(df_drop_any)<br>print(&quot;--------------------------------------------------&quot;)<br>print(&quot;\nDataFrame after dropna(axis=1, how=&#39;all&#39;):&quot;)<br>print(df_drop_col_all)<br>print(&quot;--------------------------------------------------&quot;)<br>print(&quot;\nDataFrame after dropna(thresh=3):&quot;)<br>print(df_drop_thresh)<br>print(&quot;--------------------------------------------------&quot;)<br>print(&quot;\nDataFrame after dropna(subset=[&#39;Age&#39;, &#39;City&#39;]):&quot;)<br>print(df_subset)<br>print(&quot;--------------------------------------------------&quot;)<br>print(&quot;\nDataFrame after dropna(inplace=True):&quot;)<br>print(df)</pre><pre>Original DataFrame:<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0           None    NaN<br>2  Charlie   NaN  San Francisco   88.0<br>3    David  22.0    Los Angeles    NaN<br>4   Edward   NaN        Chicago   90.0<br>--------------------------------------------------<br><br>DataFrame after dropna(how=&#39;all&#39;):<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0           None    NaN<br>2  Charlie   NaN  San Francisco   88.0<br>3    David  22.0    Los Angeles    NaN<br>4   Edward   NaN        Chicago   90.0<br>--------------------------------------------------<br><br>DataFrame after dropna(how=&#39;any&#39;):<br>    Name   Age      City  Score<br>0  Alice  24.0  New York   85.0<br>--------------------------------------------------<br><br>DataFrame after dropna(axis=1, how=&#39;all&#39;):<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0           None    NaN<br>2  Charlie   NaN  San Francisco   88.0<br>3    David  22.0    Los Angeles    NaN<br>4   Edward   NaN        Chicago   90.0<br>--------------------------------------------------<br><br>DataFrame after dropna(thresh=3):<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>2  Charlie   NaN  San Francisco   88.0<br>3    David  22.0    Los Angeles    NaN<br>4   Edward   NaN        Chicago   90.0<br>--------------------------------------------------<br>DataFrame after dropna(subset=[&#39;Age&#39;, &#39;City&#39;]):<br>Name   Age           City  Score<br>0  Alice  24.0       New York   85.0<br>3  David  22.0   Los Angeles    NaN<br>--------------------------------------------------<br>DataFrame after dropna(inplace=True):<br>Name   Age      City  Score<br>0  Alice  24.0  New York   85.0<br></pre><blockquote>fillna() — fill missing values with a specific value, the mean, median, or other statistical measures</blockquote><pre># Syntax<br>DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)<br><br># value: Scalar, dictionary, Series, or DataFrame. Specifies the value to use for filling missing values.<br># method: Method to use for filling holes in reindexed Series. Options are &#39;ffill&#39; (forward fill) or &#39;bfill&#39; (backward fill).<br># axis: Axis along which to fill missing values (0 for rows, 1 for columns).<br># inplace: If True, fills missing values in place (modifies the original DataFrame). If False, returns a new DataFrame.<br># limit: The maximum number of consecutive NaNs to fill.<br># downcast: Controls whether or not to downcast the resulting data type.<br># ffill(): Shorthand for forward filling (method=&#39;ffill&#39; in fillna()).<br># bfill(): Shorthand for backward filling (method=&#39;bfill&#39; in fillna()).</pre><p>Example</p><pre>import pandas as pd<br><br># Sample DataFrame with missing values<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Age&#39;: [24, 27, None, 22, None],<br>    &#39;City&#39;: [&#39;New York&#39;, None, &#39;San Francisco&#39;, &#39;Los Angeles&#39;, &#39;Chicago&#39;],<br>    &#39;Score&#39;: [85, None, 88, None, 90]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Fill missing values with a specific value (e.g., 0 for numerical columns)<br>df_fillna = df.fillna(0)<br><br># Display the DataFrame after fillna()<br>print(&quot;\nDataFrame after fillna(0):&quot;)<br>print(df_fillna)<br>print(&quot;--------------------------------------------------&quot;)<br><br># Forward fill missing values<br>df_ffill = df.ffill()<br><br># Display the DataFrame after ffill()<br>print(&quot;\nDataFrame after ffill():&quot;)<br>print(df_ffill)<br>print(&quot;--------------------------------------------------&quot;)<br><br># Backward fill missing values<br>df_bfill = df.bfill()<br><br># Display the DataFrame after bfill()<br>print(&quot;\nDataFrame after bfill():&quot;)<br>print(df_bfill)<br>print(&quot;--------------------------------------------------&quot;)<br><br># Fill missing values with the mean of each column<br>df_filled = df.fillna(df.mean(numeric_only=True))<br>print(df_filled)</pre><pre>Original DataFrame:<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0           None    NaN<br>2  Charlie   NaN  San Francisco   88.0<br>3    David  22.0    Los Angeles    NaN<br>4   Edward   NaN        Chicago   90.0<br><br>DataFrame after fillna(0):<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0              0    0.0<br>2  Charlie   0.0  San Francisco   88.0<br>3    David  22.0    Los Angeles    0.0<br>4   Edward   0.0        Chicago   90.0<br>--------------------------------------------------<br><br>DataFrame after ffill():<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0       New York   85.0<br>2  Charlie  27.0  San Francisco   88.0<br>3    David  22.0    Los Angeles   88.0<br>4   Edward  22.0        Chicago   90.0<br>--------------------------------------------------<br><br>DataFrame after bfill():<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob  27.0  San Francisco   88.0<br>2  Charlie  22.0  San Francisco   88.0<br>3    David  22.0    Los Angeles   90.0<br>4   Edward   NaN        Chicago   90.0<br>--------------------------------------------------<br>      Name        Age           City      Score<br>0    Alice  24.000000       New York  85.000000<br>1      Bob  27.000000           None  87.666667<br>2  Charlie  24.333333  San Francisco  88.000000<br>3    David  22.000000    Los Angeles  87.666667<br>4   Edward  24.333333        Chicago  90.000000</pre><blockquote>drop_duplicates() — remove duplicate rows from a DataFrame<br>df.duplicated() — identify duplicate rows in a DataFrame.</blockquote><pre># Syntax<br>DataFrame.drop_duplicates(subset=None, keep=&#39;first&#39;, inplace=False)<br><br># subset: Column label or sequence of labels. Only consider these columns for identifying duplicates. By default, all columns are used.<br># keep: Determines which duplicates to keep<br>       # first: (default): Keeps the first occurrence and drops subsequent duplicates.<br>       # last: Keeps the last occurrence and drops previous duplicates.<br>       # False: Drops all duplicates.<br># inplace: If True, modifies the DataFrame in place. If False (default), returns a new DataFrame.</pre><pre>import pandas as pd<br><br># Sample DataFrame with duplicate rows<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;Bob&#39;, &#39;Alice&#39;, &#39;David&#39;],<br>    &#39;Age&#39;: [24, 27, 25, 27, 24, 22],<br>    &#39;City&#39;: [&#39;New York&#39;, &#39;New York&#39;, &#39;San Francisco&#39;, &#39;New York&#39;, &#39;New York&#39;, &#39;Los Angeles&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Drop duplicate rows based on all columns, keeping the first occurrence<br>df_no_duplicates = df.drop_duplicates()<br><br># Display the DataFrame after dropping duplicates<br>print(&quot;\nDataFrame after drop_duplicates():&quot;)<br>print(df_no_duplicates)<br>print(&quot;-----------------------------------------------&quot;)<br><br># Drop duplicates based on a specific column:<br>print(&quot;\nDataFrame after drop_duplicates(subset=[&#39;Name&#39;]&quot;)<br>df_no_duplicates = df.drop_duplicates(subset=[&#39;Name&#39;])<br>print(df_no_duplicates)<br>print(&quot;-----------------------------------------------&quot;)<br><br># Keep the last occurrence instead of the first:<br>print(&quot;\nDataFrame after drop_duplicates(keep=&#39;last&#39;)&quot;)<br>df_no_duplicates = df.drop_duplicates(keep=&#39;last&#39;)<br>print(df_no_duplicates)<br>print(&quot;-----------------------------------------------&quot;)</pre><pre>Original DataFrame:<br>      Name  Age           City<br>0    Alice   24       New York<br>1      Bob   27       New York<br>2  Charlie   25  San Francisco<br>3      Bob   27       New York<br>4    Alice   24       New York<br>5    David   22    Los Angeles<br><br>DataFrame after drop_duplicates():<br>      Name  Age           City<br>0    Alice   24       New York<br>1      Bob   27       New York<br>2  Charlie   25  San Francisco<br>5    David   22    Los Angeles<br>-----------------------------------------------<br><br>DataFrame after drop_duplicates(subset=[&#39;Name&#39;]<br>      Name  Age           City<br>0    Alice   24       New York<br>1      Bob   27       New York<br>2  Charlie   25  San Francisco<br>5    David   22    Los Angeles<br>-----------------------------------------------<br><br>DataFrame after drop_duplicates(keep=&#39;last&#39;)<br>      Name  Age           City<br>2  Charlie   25  San Francisco<br>3      Bob   27       New York<br>4    Alice   24       New York<br>5    David   22    Los Angeles<br>-----------------------------------------------</pre><pre># Syntax of df.duplicated()<br>DataFrame.duplicated(subset=None, keep=&#39;first&#39;)<br><br># subset: Column label or sequence of labels. Only consider these columns for identifying duplicates. By default, all columns are used.<br># keep: Determines which duplicates to keep<br>       # first: (default): Keeps the first occurrence and drops subsequent duplicates.<br>       # last: Keeps the last occurrence and drops previous duplicates.<br>       # False: Drops all duplicates.</pre><pre>import pandas as pd<br><br># Sample DataFrame with duplicate rows<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;Bob&#39;, &#39;Alice&#39;, &#39;David&#39;],<br>    &#39;Age&#39;: [24, 27, 25, 27, 24, 22],<br>    &#39;City&#39;: [&#39;New York&#39;, &#39;New York&#39;, &#39;San Francisco&#39;, &#39;New York&#39;, &#39;New York&#39;, &#39;Los Angeles&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Identify duplicate rows<br>duplicates = df.duplicated()<br><br># Display the boolean Series indicating duplicates<br>print(&quot;\nBoolean Series of Duplicates:&quot;)<br>print(duplicates)<br>print(&quot;-----------------------------------------------&quot;)<br><br># Identify duplicates based on specific columns:<br># Only considers the Name column to identify duplicates.<br>print(&quot;\nDataFrame after duplicated(subset=[&#39;Name&#39;]&quot;)<br>duplicates = df.duplicated(subset=[&#39;Name&#39;])<br>print(duplicates)<br>print(&quot;-----------------------------------------------&quot;)<br><br># Mark duplicates except for the last occurrence:<br># Marks all occurrences of duplicates as True except for the last occurrence.<br>print(&quot;\nDataFrame after duplicated(keep=&#39;last&#39;)&quot;)<br>duplicates = df.duplicated(keep=&#39;last&#39;)<br>print(duplicates)<br>print(&quot;-----------------------------------------------&quot;)<br><br># Mark all duplicates:<br># Marks all occurrences of duplicates as True.<br>print(&quot;\nDataFrame after duplicated(keep=False)&quot;)<br>duplicates = df.duplicated(keep=False)<br>print(duplicates)<br>print(&quot;-----------------------------------------------&quot;)</pre><pre>Original DataFrame:<br>      Name  Age           City<br>0    Alice   24       New York<br>1      Bob   27       New York<br>2  Charlie   25  San Francisco<br>3      Bob   27       New York<br>4    Alice   24       New York<br>5    David   22    Los Angeles<br><br>Boolean Series of Duplicates:<br>0    False<br>1    False<br>2    False<br>3     True<br>4     True<br>5    False<br>dtype: bool<br>-----------------------------------------------<br><br>DataFrame after duplicated(subset=[&#39;Name&#39;]<br>0    False<br>1    False<br>2    False<br>3     True<br>4     True<br>5    False<br>dtype: bool<br>-----------------------------------------------<br><br>DataFrame after duplicated(keep=&#39;last&#39;)<br>0     True<br>1     True<br>2    False<br>3    False<br>4    False<br>5    False<br>dtype: bool<br>-----------------------------------------------<br><br>DataFrame after duplicated(keep=False)<br>0     True<br>1     True<br>2    False<br>3     True<br>4     True<br>5    False<br>dtype: bool<br>-----------------------------------------------</pre><blockquote>isna() and isnull() — detect missing values (NaN) in a DataFrame or Series</blockquote><pre># Syntax<br>DataFrame.isna()<br>DataFrame.isnull()<br><br># return a boolean DataFrame or Series where True indicates the presence of a missing value and False indicates a non-missing value.</pre><pre>import pandas as pd<br>import numpy as np<br><br># Sample DataFrame with missing values<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Age&#39;: [24, np.nan, 25, np.nan, 30],<br>    &#39;City&#39;: [&#39;New York&#39;, &#39;San Francisco&#39;, np.nan, &#39;Los Angeles&#39;, &#39;Chicago&#39;],<br>    &#39;Score&#39;: [85, np.nan, 88, 90, np.nan]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Detect missing values using isna()<br>print(&quot;\nMissing Values Detected with isna():&quot;)<br>print(df.isna())<br><br># Detect missing values using isnull()<br>print(&quot;\nMissing Values Detected with isnull():&quot;)<br>print(df.isnull())</pre><pre>Original DataFrame:<br>      Name   Age           City  Score<br>0    Alice  24.0       New York   85.0<br>1      Bob   NaN  San Francisco    NaN<br>2  Charlie  25.0            NaN   88.0<br>3    David   NaN    Los Angeles   90.0<br>4   Edward  30.0        Chicago    NaN<br><br>Missing Values Detected with isna():<br>    Name    Age   City  Score<br>0  False  False  False  False<br>1  False   True  False   True<br>2  False  False   True  False<br>3  False   True  False  False<br>4  False  False  False   True<br><br>Missing Values Detected with isnull():<br>    Name    Age   City  Score<br>0  False  False  False  False<br>1  False   True  False   True<br>2  False  False   True  False<br>3  False   True  False  False<br>4  False  False  False   True</pre><blockquote>notna() / notnull() — detect non-missing values in a DataFrame or Series. They are essentially the opposite of isna() and isnull(), returning True for entries that are not missing and False for entries that are missing.</blockquote><blockquote><strong>replace()</strong> — replace specified values in a DataFrame or Series with new values. This is useful for cleaning and modifying data by replacing specific values, such as missing values or erroneous entries, with more appropriate values.</blockquote><pre># Syntax<br>DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None)<br>Series.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=None)<br><br># to_replace: Value or list of values to be replaced. It can also be a dictionary where keys are the values to replace and values are the new values.<br># value: New value to replace to_replace. If to_replace is a dictionary, this parameter is not used.<br># inplace: If True, modifies the DataFrame or Series in place. If False (default), returns a new DataFrame or Series.<br># limit: Maximum number of replacements to make.<br># regex: If True, interprets to_replace and value as regular expressions.<br># method: The method to use for filling missing values (&#39;ffill&#39; or &#39;bfill&#39;). This parameter is usually not used with replace().</pre><pre>import pandas as pd<br><br># Sample DataFrame<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Age&#39;: [24, 27, 21, 22, 24],<br>    &#39;City&#39;: [&#39;New York&#39;, &#39;San Francisco&#39;, &#39;San Francisco&#39;, &#39;Los Angeles&#39;, &#39;New York&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Replace specific values<br>df_replaced = df.replace({&#39;Age&#39;: {24: 26}, &#39;City&#39;: &#39;San Francisco&#39;}, {&#39;City&#39;: &#39;SF&#39;})<br><br># Display the DataFrame after replacement<br>print(&quot;\nDataFrame after replace():&quot;)<br>print(df_replaced)</pre><pre>Original DataFrame:<br>      Name  Age           City<br>0    Alice   24       New York<br>1      Bob   27  San Francisco<br>2  Charlie   21  San Francisco<br>3    David   22    Los Angeles<br>4   Edward   24       New York<br><br>DataFrame after replace():<br>      Name  Age         City<br>0    Alice   26     New York<br>1      Bob   27           SF<br>2  Charlie   21           SF<br>3    David   22  Los Angeles<br>4   Edward   26     New York</pre><p>Using the replace() function with the regex parameter allows you to perform replacements based on regular expressions. This can be useful for more complex patterns or for replacing multiple variations of a pattern with a single value.</p><p>Replacing Special Character in dataframe</p><pre>import pandas as pd<br><br># Sample DataFrame with special characters<br>data = {<br>    &#39;Text&#39;: [&#39;hello@world!&#39;, &#39;good#morning$&#39;, &#39;check*this^out&#39;, &#39;Python&amp;Data*Science&#39;, &#39;data@2024&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Replace special characters using regex<br>df_replaced = df.replace(r&#39;[^\w\s]&#39;, &#39;&#39;, regex=True)<br><br># Display the DataFrame after replacement<br>print(&quot;\nDataFrame after replace() with regex to remove special characters:&quot;)<br>print(df_replaced)</pre><pre>Original DataFrame:<br>                  Text<br>0         hello@world!<br>1        good#morning$<br>2       check*this^out<br>3  Python&amp;Data*Science<br>4            data@2024<br><br>DataFrame after replace() with regex to remove special characters:<br>                Text<br>0         helloworld<br>1        goodmorning<br>2       checkthisout<br>3  PythonDataScience<br>4           data2024</pre><p><strong>Pattern Used</strong>: r&#39;[^\w\s]&#39;</p><p>[^\w\s]: Matches any character that is not a word character (\w) or whitespace (\s). This effectively matches special characters and punctuation.</p><p>Replacement: Replaces all special characters with an empty string (&#39;&#39;), effectively removing them.</p><p>Example 2</p><pre>import pandas as pd<br><br># Sample DataFrame<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;, &#39;Edward&#39;],<br>    &#39;Address&#39;: [&#39;123 Main St&#39;, &#39;456 Elm St&#39;, &#39;789 Oak St&#39;, &#39;123 Maple St&#39;, &#39;456 Pine St&#39;]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Replace street names using regex to standardize them<br>df_replaced = df.replace({&#39;Address&#39;: r&#39;\d{3} (Main|Elm|Oak|Maple|Pine) St&#39;}, &#39;Standard St&#39;, regex=True)<br><br># Display the DataFrame after replacement<br>print(&quot;\nDataFrame after replace() with regex:&quot;)<br>print(df_replaced)</pre><pre>Original DataFrame:<br>      Name       Address<br>0    Alice   123 Main St<br>1      Bob    456 Elm St<br>2  Charlie    789 Oak St<br>3    David  123 Maple St<br>4   Edward   456 Pine St<br><br>DataFrame after replace() with regex:<br>      Name      Address<br>0    Alice  Standard St<br>1      Bob  Standard St<br>2  Charlie  Standard St<br>3    David  Standard St<br>4   Edward  Standard St</pre><p>Pattern Used: r’\d{3} (Main|Elm|Oak|Maple|Pine) St’</p><p>\d{3}: Matches exactly three digits.<br>(Main|Elm|Oak|Maple|Pine): Matches any of the specified street names.<br>St: Matches the literal string ‘St’.</p><p>Replacement: All addresses that match this pattern are replaced with ‘Standard St’.</p><blockquote>astype() — Changes the data type of a DataFrame column.</blockquote><pre># Syntax<br>DataFrame.astype(dtype, copy=True, errors=&#39;raise&#39;)<br><br># dtype: Data type to which you want to cast. It can be a single type or a dictionary specifying types for each column.<br># copy: If True (default), always returns a new object. If False, it tries to avoid copying data if possible.<br># errors: Determines what to do if the conversion fails:<br>    # &#39;raise&#39; (default): Raise an error if conversion fails.<br>    # &#39;ignore&#39;: Ignore errors and return the original object.</pre><pre>import pandas as pd<br><br># Sample DataFrame with mixed types<br>data = {<br>    &#39;A&#39;: [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;],<br>    &#39;B&#39;: [&#39;4.5&#39;, &#39;5.5&#39;, &#39;6.5&#39;],<br>    &#39;C&#39;: [True, False, True]<br>}<br><br>df = pd.DataFrame(data)<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br><br># Convert column &#39;A&#39; to integers, &#39;B&#39; to floats<br>df_converted = df.astype({&#39;A&#39;: &#39;int&#39;, &#39;B&#39;: &#39;float&#39;})<br><br># Display the DataFrame after conversion<br>print(&quot;\nDataFrame after astype():&quot;)<br>print(df_converted)</pre><pre>Original DataFrame:<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3 entries, 0 to 2<br>Data columns (total 3 columns):<br> #   Column  Non-Null Count  Dtype <br>---  ------  --------------  ----- <br> 0   A       3 non-null      object<br> 1   B       3 non-null      object<br> 2   C       3 non-null      bool  <br>dtypes: bool(1), object(2)<br>memory usage: 183.0+ bytes<br>None<br><br>DataFrame after astype():<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3 entries, 0 to 2<br>Data columns (total 3 columns):<br> #   Column  Non-Null Count  Dtype  <br>---  ------  --------------  -----  <br> 0   A       3 non-null      int64  <br> 1   B       3 non-null      float64<br> 2   C       3 non-null      bool   <br>dtypes: bool(1), float64(1), int64(1)<br>memory usage: 183.0 bytes<br>None</pre><p>Date Time conversion example</p><pre># Sample DataFrame with date strings<br>df = pd.DataFrame({<br>    &#39;Date&#39;: [&#39;2024-08-17&#39;, &#39;2024-08-18&#39;, &#39;2024-08-19&#39;],<br>    &#39;Value&#39;: [10, 20, 30]<br>})<br><br># Display the original DataFrame<br>print(&quot;Original DataFrame:&quot;)<br>print(df)<br>print(df.info())<br><br>print(&quot;----------------------------------------------&quot;)<br># Convert &#39;Date&#39; column to datetime<br>df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;])<br><br># Display the DataFrame after conversion<br>print(&quot;\nDataFrame after pd.to_datetime():&quot;)<br>print(df)<br>print(df.info())</pre><pre>Original DataFrame:<br>         Date  Value<br>0  2024-08-17     10<br>1  2024-08-18     20<br>2  2024-08-19     30<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3 entries, 0 to 2<br>Data columns (total 2 columns):<br> #   Column  Non-Null Count  Dtype <br>---  ------  --------------  ----- <br> 0   Date    3 non-null      object<br> 1   Value   3 non-null      int64 <br>dtypes: int64(1), object(1)<br>memory usage: 180.0+ bytes<br>None<br>----------------------------------------------<br><br>DataFrame after pd.to_datetime():<br>        Date  Value<br>0 2024-08-17     10<br>1 2024-08-18     20<br>2 2024-08-19     30<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 3 entries, 0 to 2<br>Data columns (total 2 columns):<br> #   Column  Non-Null Count  Dtype         <br>---  ------  --------------  -----         <br> 0   Date    3 non-null      datetime64[ns]<br> 1   Value   3 non-null      int64         <br>dtypes: datetime64[ns](1), int64(1)<br>memory usage: 180.0 bytes<br>None</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18029f8f0436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Read Function]]></title>
            <link>https://medium.com/@nmehta1004/pandas-read-function-fa9611c81fa4?source=rss-2c20a754a54e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa9611c81fa4</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-tutorial]]></category>
            <dc:creator><![CDATA[Nirav Mehta]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 14:27:40 GMT</pubDate>
            <atom:updated>2024-08-15T14:28:52.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92eZZ3CUvFJ27CcofW5thg.png" /></figure><p>This article will delve into various sources from where pandas can read data and convert it into Series or DataFrame</p><p>Pandas is a highly flexible library that can read data from a wide variety of sources and convert it into Series or DataFrames for further manipulation and analysis. Here are some of the most common sources from which Pandas can read data:</p><blockquote>CSV Files</blockquote><blockquote>Pandas can easily read data from CSV (Comma-Separated Values) files, which are one of the most common data formats.</blockquote><pre>df = pd.read_csv(&#39;data.csv&#39;)</pre><blockquote>Excel Files</blockquote><p>Pandas can read data from Excel files (both .xls and .xlsx formats). It can also handle multiple sheets.</p><pre>df = pd.read_excel(&#39;data.xlsx&#39;, sheet_name=&#39;Sheet1&#39;)</pre><blockquote>JSON Files</blockquote><p>JSON (JavaScript Object Notation) is a popular data format for web applications. Pandas can convert JSON data into DataFrames.</p><pre>df = pd.read_json(&#39;data.json&#39;)</pre><blockquote>SQL Databases</blockquote><p>Pandas can read data from SQL databases using SQL queries or directly from tables. This requires a connection to the database using a library like SQLAlchemy.</p><pre>from sqlalchemy import create_engine<br><br>engine = create_engine(&#39;sqlite:///mydatabase.db&#39;)<br>df = pd.read_sql(&#39;SELECT * FROM table_name&#39;, con=engine)<br></pre><blockquote>HTML Tables</blockquote><p>Pandas can extract tables directly from HTML pages and convert them into DataFrames.</p><pre>url = &#39;https://example.com/data.html&#39;<br>df_list = pd.read_html(url)  # Returns a list of DataFrames<br>df = df_list[0]  # Accessing the first table<br></pre><blockquote>API Calls (Web Services)</blockquote><p>You can make API calls using the requests library, retrieve JSON or XML data, and convert it into a Pandas DataFrame.</p><pre>import requests<br>import pandas as pd<br><br>response = requests.get(&#39;https://api.example.com/data&#39;)<br>data = response.json()<br>df = pd.DataFrame(data)</pre><blockquote>Google Cloud Storage</blockquote><p>To Read CSV file from Google Cloud Storage, install gcsfs library</p><pre>import pandas as pd<br><br># Install gcsfs if not already installed<br># !pip install gcsfs<br><br># Read CSV file from Google Cloud Storage<br>df = pd.read_csv(&#39;gs://your-bucket-name/path/to/your-file.csv&#39;)<br>print(df.head())</pre><blockquote>Amazon S3</blockquote><p>To read data from S3 bucket, install boto3 and s3fs libraries.</p><pre>import pandas as pd<br><br># Install boto3 and s3fs if not already installed<br># !pip install boto3 s3fs<br><br># Read CSV file from Amazon S3<br>df = pd.read_csv(&#39;s3://your-bucket-name/path/to/your-file.csv&#39;)<br>print(df.head())</pre><blockquote>Azure Blob Storage</blockquote><p>To read data from Azure blob storage, install azure-storage-blob and fsspec libraries.</p><pre>import pandas as pd<br>from azure.storage.blob import BlobServiceClient<br>from fsspec import filesystem<br><br># Install azure-storage-blob and fsspec if not already installed<br># !pip install azure-storage-blob fsspec<br><br># Set up connection<br>connection_string = &quot;your-azure-connection-string&quot;<br>fs = filesystem(&#39;abfs&#39;, connection_string=connection_string)<br><br># Read CSV file from Azure Blob Storage<br>df = pd.read_csv(&#39;abfs://your-container-name/path/to/your-file.csv&#39;, storage_options={&#39;connection_string&#39;: connection_string})<br>print(df.head())</pre><blockquote>Dropbox</blockquote><p>To read data from Dropbox, install ropbox and fsspec libraries.</p><pre>import pandas as pd<br><br># Install dropbox and fsspec if not already installed<br># !pip install dropbox fsspec<br><br># Read CSV file from Dropbox<br>df = pd.read_csv(&#39;dropbox://path/to/your-file.csv&#39;, storage_options={&#39;token&#39;: &#39;your-access-token&#39;})<br>print(df.head())</pre><blockquote>OneDrive</blockquote><p>To read data from OndDrive, install onedrivesdk and fsspec libraries</p><pre>import pandas as pd<br><br># Install onedrivesdk and fsspec if not already installed<br># !pip install onedrivesdk fsspec<br><br># Read CSV file from OneDrive<br>df = pd.read_csv(&#39;onedrive://path/to/your-file.csv&#39;, storage_options={&#39;access_token&#39;: &#39;your-access-token&#39;})<br>print(df.head())</pre><blockquote>Google Sheets</blockquote><p>By using the gspread library, you can interact with Google Sheets and then convert the data into a Pandas DataFrame.</p><pre>import gspread<br>import pandas as pd<br><br>gc = gspread.service_account(filename=&#39;path_to_credentials.json&#39;)<br>sh = gc.open(&#39;GoogleSheetName&#39;)<br>worksheet = sh.sheet1<br>df = pd.DataFrame(worksheet.get_all_records())  </pre><blockquote>XML Files</blockquote><p>XML (eXtensible Markup Language) is a common data format for structured data. Pandas can read XML data into DataFrames.</p><pre>df = pd.read_xml(&#39;data.xml&#39;)</pre><blockquote>Parquet Files</blockquote><p>Parquet is a columnar storage file format optimized for large-scale data processing. Pandas can read Parquet files, which are often used in big data environments.</p><pre>df = pd.read_parquet(&#39;data.parquet&#39;)</pre><blockquote>HDF5 Files</blockquote><p>HDF5 is a file format for storing large amounts of data. Pandas can read from HDF5 files, which are often used in scientific computing.</p><pre>df = pd.read_hdf(&#39;data.h5&#39;, key=&#39;dataset_name&#39;)</pre><blockquote>Pickle Files</blockquote><p>Pandas can read data from pickle files, which are Python’s serialized data format. This is useful for saving and loading Python objects.</p><pre>df = pd.read_pickle(&#39;data.pkl&#39;)</pre><blockquote>Clipboard</blockquote><p>Pandas can read data copied to your clipboard and convert it into a DataFrame. This is useful for quick data imports from spreadsheets or web pages.</p><pre>df = pd.read_clipboard()</pre><blockquote>Google BigQuery</blockquote><p>Pandas can read data from Google BigQuery, a cloud-based big data analytics web service, directly into a DataFrame.</p><pre>df = pd.read_gbq(&#39;SELECT * FROM dataset.table&#39;, project_id=&#39;my-project-id&#39;)</pre><blockquote>SAS Files</blockquote><p>Pandas can read SAS (Statistical Analysis System) files, which are used for advanced analytics, multivariate analysis, and business intelligence</p><pre>df = pd.read_sas(&#39;data.sas7bdat&#39;)</pre><blockquote>Stata Files</blockquote><p>Stata is a statistical software package, and Pandas can read Stata files into DataFrames.</p><pre>df = pd.read_stata(&#39;data.dta&#39;)</pre><blockquote>SPSS Files</blockquote><p>Pandas can read data from SPSS (Statistical Package for the Social Sciences) files.</p><pre>df = pd.read_spss(&#39;data.sav&#39;)</pre><blockquote>Feather Files</blockquote><p>Feather is a fast binary columnar data format. Pandas can read Feather files efficiently into DataFrames.</p><pre>df = pd.read_feather(&#39;data.feather&#39;)</pre><blockquote>ORC Files</blockquote><p>ORC (Optimized Row Columnar) format is a highly optimized file format for large datasets. Pandas can read ORC files, commonly used in big data contexts.</p><pre>df = pd.read_orc(&#39;data.orc&#39;)</pre><blockquote>Avro Files</blockquote><p>Avro is a data serialization framework that uses JSON for defining data types and protocols. Pandas can read Avro files into DataFrames.</p><pre>df = pd.read_avro(&#39;data.avro&#39;)</pre><h3>Conclusion</h3><p>Pandas provides extensive support for reading data from various sources, making it incredibly versatile for data engineering and analysis tasks. Whether you’re dealing with structured data like CSVs and SQL databases or more complex formats like JSON, XML, or Parquet, Pandas allows you to easily convert this data into Series or DataFrames for further processing. Understanding the different sources Pandas can read from enables you to integrate diverse datasets into your workflows, making data manipulation and analysis more seamless and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa9611c81fa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Data Structure]]></title>
            <link>https://medium.com/@nmehta1004/pandas-data-structure-c91768be177e?source=rss-2c20a754a54e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c91768be177e</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas-tutorial]]></category>
            <category><![CDATA[dataframes-python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Nirav Mehta]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 07:12:38 GMT</pubDate>
            <atom:updated>2024-08-15T07:15:04.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92eZZ3CUvFJ27CcofW5thg.png" /></figure><p>This article will delve into Pandas Data Structures, how to create Series and DataFrame and basic Operations on Series and DataFrame.</p><p>Pandas provides two primary data structures that form the backbone of its data manipulation capabilities: <strong>Series</strong> and <strong>DataFrame</strong>. These structures are designed to handle and analyze data efficiently, making them essential tools for data engineers, data scientists, and analysts. Let’s dive into each of these data structures in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*gRimEMk9obqsPenR_e4Miw.png" /></figure><h3>1. Pandas Series</h3><p>A <strong>Series</strong> is a one-dimensional array-like object that can hold data of any type, such as integers, floats, strings, or even Python objects. It is similar to a column in a spreadsheet or a SQL table. Each element in a Series is associated with an index, which labels the data, making it easy to access and manipulate specific elements.</p><h4>Key Characteristics of Series:</h4><ul><li><strong>One-Dimensional</strong>: A Series is a single column of data.</li><li><strong>Homogeneous Data</strong>: All elements in a Series are of the same data type.</li><li><strong>Indexing</strong>: Each element in a Series is associated with an index, which can be explicitly defined or automatically assigned.</li><li><strong>Data Types</strong>: A Series can hold data of various types, including integers, floats, strings, and even Python objects.</li></ul><h4>Creating a Series:</h4><pre>import pandas as pd<br><br># Creating a Series from a list<br>s = pd.Series([1, 2, 3, 4, 5])<br><br># Creating a Series with a custom index<br>s_custom_index = pd.Series([10, 20, 30, 40, 50], index=[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;])<br><br># Printing Output of entire series<br>print(&quot;Series with default Index&quot;)<br>print(s)<br>print(&quot;-----------------------------------&quot;)<br><br>print(&quot;Series with custom Index&quot;)<br>print(s_custom_index)<br>print(&quot;-----------------------------------&quot;)<br><br># Accessing elements<br>print(&quot;Accessing elements by position&quot;)<br>print(s[0])  <br>print(&quot;-----------------------------------&quot;)<br><br>print(&quot;# Accessing elements by custom index&quot;)<br>print(s_custom_index[&#39;c&#39;])<br>print(&quot;-----------------------------------&quot;)</pre><pre>Series with default Index<br>0    1<br>1    2<br>2    3<br>3    4<br>4    5<br>dtype: int64<br>-----------------------------------<br>Series with custom Index<br>a    10<br>b    20<br>c    30<br>d    40<br>e    50<br>dtype: int64<br>-----------------------------------<br>Accessing elements by position<br>1<br>-----------------------------------<br># Accessing elements by custom index<br>30</pre><h3>2. Pandas DataFrame</h3><p>A <strong>DataFrame</strong> is a two-dimensional, tabular data structure that consists of rows and columns. It is the most commonly used pandas data structure and is analogous to a table in a relational database or an Excel spreadsheet. A DataFrame is essentially a collection of Series objects that share the same index.</p><h4>Key Characteristics of DataFrame:</h4><ul><li><strong>Two-Dimensional</strong>: Data is organized in rows and columns.</li><li><strong>Heterogeneous Data</strong>: Different columns can contain different data types (e.g., integers, floats, strings).</li><li><strong>Indexing</strong>: Like Series, each row and column in a DataFrame is indexed. The row index is called the “index,” and the column index is referred to as the “column labels.”</li><li><strong>Data Alignment</strong>: Operations on DataFrames automatically align the data by labels (index and columns).</li></ul><h4>Creating a DataFrame:</h4><pre>import pandas as pd<br><br># Creating a DataFrame from a dictionary of lists<br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;],<br>    &#39;Age&#39;: [24, 27, 22, 32],<br>    &#39;Salary&#39;: [50000, 54000, 52000, 58000]<br>}<br>df = pd.DataFrame(data)<br><br>print(df.to_string())<br>print(&quot;---------------------------------------&quot;)<br><br># Creating a DataFrame from a list of dictionaries<br>data = [<br>    {&#39;Name&#39;: &#39;Alice&#39;, &#39;Age&#39;: 24, &#39;Salary&#39;: 50000},<br>    {&#39;Name&#39;: &#39;Bob&#39;, &#39;Age&#39;: 27, &#39;Salary&#39;: 54000},<br>    {&#39;Name&#39;: &#39;Charlie&#39;, &#39;Age&#39;: 22, &#39;Salary&#39;: 52000},<br>    {&#39;Name&#39;: &#39;David&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 58000}<br>]<br>df = pd.DataFrame(data)<br>print(df.to_string())<br>print(&quot;---------------------------------------&quot;)</pre><pre>      Name  Age  Salary<br>0    Alice   24   50000<br>1      Bob   27   54000<br>2  Charlie   22   52000<br>3    David   32   58000<br>---------------------------------------<br>      Name  Age  Salary<br>0    Alice   24   50000<br>1      Bob   27   54000<br>2  Charlie   22   52000<br>3    David   32   58000<br>---------------------------------------</pre><pre># Accessing a single column (returns a Series)<br>print(&quot;---------------------------------------&quot;)<br>print(df[&#39;Name&#39;])<br>print(&quot;---------------------------------------&quot;)<br>print(type(df[&#39;Name&#39;]))<br>print(&quot;---------------------------------------&quot;)<br><br># Accessing multiple columns (returns a DataFrame)<br>print(df[[&#39;Name&#39;, &#39;Salary&#39;]])<br>print(&quot;---------------------------------------&quot;)<br>print(type(df[[&#39;Name&#39;, &#39;Salary&#39;]]))<br>print(&quot;---------------------------------------&quot;)<br><br># Accessing rows by index<br>print(df.loc[0])  # Using label-based indexing (returns a Series)<br>print(&quot;---------------------------------------&quot;)<br>print(df.iloc[0])  # Using position-based indexing (returns a Series)<br>print(&quot;---------------------------------------&quot;)</pre><pre>---------------------------------------<br>0      Alice<br>1        Bob<br>2    Charlie<br>3      David<br>Name: Name, dtype: object<br>---------------------------------------<br>&lt;class &#39;pandas.core.series.Series&#39;&gt;<br>---------------------------------------<br>      Name  Salary<br>0    Alice   50000<br>1      Bob   54000<br>2  Charlie   52000<br>3    David   58000<br>---------------------------------------<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>---------------------------------------<br>Name      Alice<br>Age          24<br>Salary    50000<br>Name: 0, dtype: object<br>---------------------------------------<br>Name      Alice<br>Age          24<br>Salary    50000<br>Name: 0, dtype: object<br>---------------------------------------</pre><blockquote>The Importance of Indexing</blockquote><p>Both Series and DataFrame structures use indexing to enhance data accessibility and manipulation. The index in pandas serves as a unique identifier for data points and allows for more efficient data alignment during operations. Users can customize indexes to reflect specific attributes of the data, such as dates, labels, or unique identifiers.</p><blockquote>MultiIndex in Pandas</blockquote><p>Pandas also supports <strong>MultiIndex</strong>, which allows for multiple levels of indexing on rows and columns. This is particularly useful when working with high-dimensional data.</p><h4>Creating a MultiIndex DataFrame:</h4><pre>import pandas as pd<br><br># Creating a MultiIndex DataFrame<br>arrays = [<br>    [&#39;A&#39;, &#39;A&#39;, &#39;B&#39;, &#39;B&#39;],<br>    [&#39;one&#39;, &#39;two&#39;, &#39;one&#39;, &#39;two&#39;]<br>]<br>index = pd.MultiIndex.from_arrays(arrays, names=(&#39;Group&#39;, &#39;Subgroup&#39;))<br>data = {&#39;Data&#39;: [10, 20, 30, 40]}<br>df_multi = pd.DataFrame(data, index=index)<br>print(&quot;---------------------------------------&quot;)<br>print(df_multi.to_string())<br>print(&quot;---------------------------------------&quot;)<br># Accessing data using the MultiIndex<br>print(df_multi.loc[&#39;A&#39;])<br>print(&quot;---------------------------------------&quot;)<br>print(df_multi.loc[(&#39;A&#39;, &#39;one&#39;)])<br>print(&quot;---------------------------------------&quot;)</pre><pre>---------------------------------------<br>                Data<br>Group Subgroup      <br>A     one         10<br>      two         20<br>B     one         30<br>      two         40<br>---------------------------------------<br>          Data<br>Subgroup      <br>one         10<br>two         20<br>---------------------------------------<br>Data    10<br>Name: (A, one), dtype: int64<br>---------------------------------------</pre><blockquote>Basic Operation on DataFrame</blockquote><pre>data = [<br>    {&#39;Name&#39;: &#39;Alice&#39;, &#39;Age&#39;: 24, &#39;Salary&#39;: 50000},<br>    {&#39;Name&#39;: &#39;Bob&#39;, &#39;Age&#39;: 27, &#39;Salary&#39;: 54000},<br>    {&#39;Name&#39;: &#39;Charlie&#39;, &#39;Age&#39;: 22, &#39;Salary&#39;: 52000},<br>    {&#39;Name&#39;: &#39;David&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 58000},<br>    {&#39;Name&#39;: &#39;Sachin&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 60000},<br>    {&#39;Name&#39;: &#39;Virat&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 58000},<br>    {&#39;Name&#39;: &#39;Rohit&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 56000},<br>    {&#39;Name&#39;: &#39;Rahul&#39;, &#39;Age&#39;: 32, &#39;Salary&#39;: 60000},<br>    {&#39;Name&#39;: &#39;Rahul&#39;, &#39;Age&#39;: 32 }<br>    <br>]<br>df = pd.DataFrame(data)<br>print(&quot;---------------------------&quot;)<br>print(df.to_string())<br>print(&quot;---------------------------&quot;)<br># show top 3 rows from dataframe<br>print(df.head(3).to_string())<br>print(&quot;---------------------------&quot;)<br># show last 3 rows from dataframe<br>print(df.tail(3).to_string())</pre><pre>---------------------------<br>      Name  Age   Salary<br>0    Alice   24  50000.0<br>1      Bob   27  54000.0<br>2  Charlie   22  52000.0<br>3    David   32  58000.0<br>4   Sachin   32  60000.0<br>5    Virat   32  58000.0<br>6    Rohit   32  56000.0<br>7    Rahul   32  60000.0<br>8    Rahul   32      NaN<br>---------------------------<br>      Name  Age   Salary<br>0    Alice   24  50000.0<br>1      Bob   27  54000.0<br>2  Charlie   22  52000.0<br>---------------------------<br>    Name  Age   Salary<br>6  Rohit   32  56000.0<br>7  Rahul   32  60000.0<br>8  Rahul   32      NaN</pre><blockquote><strong>df.info()</strong></blockquote><p>The df.info() method in pandas is a very useful function that provides a concise summary of a DataFrame. Here&#39;s what it typically includes:</p><ul><li><strong>Index Information</strong>: It shows the range of the index, indicating the total number of entries (rows).</li><li><strong>Column Information</strong>: The name of each column, number of non-null entries in each column, data type (dtype) of each column.</li><li><strong>Memory Usage</strong>: It displays the amount of memory used by the DataFrame. You can see the memory usage in bytes by default, but you can get a more human-readable format (e.g., in MB) by setting the memory_usage=&#39;deep&#39; argument.</li></ul><p>This output provides a quick overview of the DataFrame’s structure, helping you understand its size, the types of data it contains, and whether there are any missing values.</p><pre># Salary no added for one item so same is taken as NAN and its value is null<br># Output of df.(info) command shows non-null values as 3 for Salary column<br>data = [<br>    {&#39;Name&#39;: &#39;Alice&#39;, &#39;Age&#39;: 24, &#39;Salary&#39;: 50000},<br>    {&#39;Name&#39;: &#39;Bob&#39;, &#39;Age&#39;: 27, &#39;Salary&#39;: 54000},<br>    {&#39;Name&#39;: &#39;Charlie&#39;, &#39;Age&#39;: 22, &#39;Salary&#39;: 52000},<br>    {&#39;Name&#39;: &#39;Rahul&#39;, &#39;Age&#39;: 32 }<br>    <br>]<br>df = pd.DataFrame(data)<br>print(df.info())</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 4 entries, 0 to 3<br>Data columns (total 3 columns):<br> #   Column  Non-Null Count  Dtype  <br>---  ------  --------------  -----  <br> 0   Name    4 non-null      object <br> 1   Age     4 non-null      int64  <br> 2   Salary  3 non-null      float64<br>dtypes: float64(1), int64(1), object(1)<br>memory usage: 228.0+ bytes<br>None</pre><blockquote><strong>df.describe()</strong></blockquote><p>The df.describe() method in pandas generates descriptive statistics that summarize the central tendency, dispersion, and shape of a dataset’s distribution, excluding NaN values. It’s a quick way to get an overview of your numerical data.</p><p><strong>What </strong><strong>df.describe() Provides:</strong></p><ul><li><strong>Count</strong>: The number of non-null entries for each column.</li><li><strong>Mean</strong>: The average of the values in each column.</li><li><strong>Std</strong>: The standard deviation, which measures the spread of the data around the mean.</li><li><strong>Min</strong>: The minimum value in each column.</li><li><strong>25%</strong>: The 25th percentile, also known as the first quartile.</li><li><strong>50%</strong>: The 50th percentile, or median, which divides the data into two halves.</li><li><strong>75%</strong>: The 75th percentile, also known as the third quartile.</li><li><strong>Max</strong>: The maximum value in each column.</li></ul><pre>import pandas as pd<br><br># Sample DataFrame<br>data = {<br>    &#39;A&#39;: [1, 2, 3, 4, 5],<br>    &#39;B&#39;: [10.1, 20.2, 30.3, 40.4, 50.5],<br>    &#39;C&#39;: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]<br>}<br><br>df = pd.DataFrame(data)<br>print(&quot;---------------------------&quot;)<br># Getting descriptive statistics<br># By default, df.describe() only analyzes numerical columns.<br>print(df.describe())<br>print(&quot;---------------------------&quot;)<br># If you want to include all columns, you can use the argument include=&#39;all&#39;<br>print(df.describe(include=&#39;all&#39;))<br>print(&quot;---------------------------&quot;)</pre><pre>---------------------------<br>              A          B<br>count  5.000000   5.000000<br>mean   3.000000  30.300000<br>std    1.581139  15.969502<br>min    1.000000  10.100000<br>25%    2.000000  20.200000<br>50%    3.000000  30.300000<br>75%    4.000000  40.400000<br>max    5.000000  50.500000<br>-------------------------------------<br>               A          B    C<br>count   5.000000   5.000000    5<br>unique       NaN        NaN    5<br>top          NaN        NaN    a<br>freq         NaN        NaN    1<br>mean    3.000000  30.300000  NaN<br>std     1.581139  15.969502  NaN<br>min     1.000000  10.100000  NaN<br>25%     2.000000  20.200000  NaN<br>50%     3.000000  30.300000  NaN<br>75%     4.000000  40.400000  NaN<br>max     5.000000  50.500000  NaN<br>---------------------------------------</pre><blockquote><strong>df.shape</strong></blockquote><p>df.shape is an attribute (not a method) that returns a tuple representing the dimensions of a DataFrame. Specifically, it provides the number of rows and columns in the DataFrame.</p><pre>import pandas as pd<br><br># Sample DataFrame<br>data = {<br>    &#39;A&#39;: [1, 2, 3, 4, 5],<br>    &#39;B&#39;: [10.1, 20.2, 30.3, 40.4, 50.5],<br>    &#39;C&#39;: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]<br>}<br><br>df = pd.DataFrame(data)<br>print(df.shape)</pre><pre>(5, 3)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c91768be177e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Pandas for Data Engineering]]></title>
            <link>https://medium.com/@nmehta1004/python-pandas-for-data-engineering-ed17fa3bac1f?source=rss-2c20a754a54e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed17fa3bac1f</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nirav Mehta]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 09:20:54 GMT</pubDate>
            <atom:updated>2024-08-15T07:14:23.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92eZZ3CUvFJ27CcofW5thg.png" /></figure><p>Python has become a go-to language for data professionals due to its versatility, ease of use, and powerful libraries. Among these libraries, <strong>Pandas</strong> stands out as one of the most essential tools for data engineers, data scientists, and analysts alike. This article will delve into the role of Pandas in data engineering, exploring what Pandas is, the benefits it offers, why it’s widely used, and scenarios where it might not be the best tool for the job.</p><blockquote><strong>What is Pandas?</strong></blockquote><p>Pandas is an open-source data manipulation and analysis library for Python, providing high-performance, easy-to-use data structures, and data analysis tools. At its core, Pandas introduces two primary data structures: <strong>Series</strong> (one-dimensional) and <strong>DataFrame</strong> (two-dimensional). These structures allow users to store and manipulate large datasets efficiently, making it easier to perform a wide range of data engineering tasks, from data cleaning and transformation to aggregation and visualization.</p><blockquote><strong>Benefits of Using Pandas</strong></blockquote><ol><li><strong>Ease of Use</strong>: Pandas offers a user-friendly API that simplifies complex data manipulation tasks. Its intuitive syntax allows for the rapid development and testing of data pipelines, making it accessible even to those new to programming.</li><li><strong>Flexibility</strong>: Pandas supports a variety of data formats, including CSV, Excel, SQL databases, JSON, and more. This flexibility makes it easy to import, export, and manipulate data from diverse sources.</li><li><strong>Efficient Data Handling</strong>: Pandas is designed for efficient data manipulation. It can handle large datasets and perform operations such as filtering, grouping, and aggregating with minimal code, reducing the need for manual processing.</li><li><strong>Powerful Data Transformation Capabilities</strong>: With Pandas, data engineers can perform complex transformations, such as pivoting, melting, merging, and joining data. These operations are essential for preparing data for downstream processes like machine learning or reporting.</li><li><strong>Integration with Other Python Libraries</strong>: Pandas integrates seamlessly with other Python libraries, such as NumPy for numerical operations, Matplotlib and Seaborn for data visualization, and Scikit-learn for machine learning. This ecosystem allows for end-to-end data engineering workflows within Python.</li></ol><blockquote><strong>Why Use Pandas?</strong></blockquote><p>Pandas is ideal for data engineering tasks that require quick, iterative development and analysis. It excels in scenarios where you need to:</p><ul><li><strong>Clean and Prepare Data</strong>: Pandas simplifies handling missing data, filtering out unwanted records, and standardizing data formats.</li><li><strong>Transform and Aggregate Data</strong>: Its powerful group-by and pivot functionalities allow for complex data aggregation and transformation tasks.</li><li><strong>Analyze and Explore Data</strong>: With Pandas, you can easily generate summary statistics, explore data distributions, and visualize data trends.</li></ul><blockquote><strong>Most Important benefits of Pandas</strong></blockquote><p>Pandas is known for its speed and efficiency in data manipulation, which can be attributed to several key factors:</p><ol><li><strong>Efficient Data Structures</strong></li></ol><p><strong>NumPy Arrays</strong>: Pandas is built on top of NumPy, which provides fast, efficient array operations. The core data structures in Pandas (Series and DataFrame) are essentially wrappers around NumPy arrays, benefiting from NumPy’s optimized performance for numerical computations.</p><p><strong>Columnar Storage</strong>: Pandas DataFrame stores data in a columnar format rather than row-wise. This columnar storage format allows for efficient operations on individual columns, especially for vectorized operations and aggregation tasks.</p><p><strong>2. Vectorized Operations</strong></p><p><strong>Vectorization</strong>: Pandas leverages vectorized operations through NumPy, which allows you to perform operations on entire arrays (or columns) at once. This is much faster than using Python loops to iterate over individual elements.</p><p><strong>Broadcasting</strong>: NumPy’s broadcasting rules enable efficient operations on arrays of different shapes without the need for explicit loops, further speeding up computations.</p><p><strong>3. Optimized Algorithms</strong></p><p><strong>Efficient Algorithms</strong>: Pandas implements many optimized algorithms for common data manipulation tasks like sorting, grouping, and merging. These algorithms are designed to handle large datasets efficiently.</p><p><strong>Cython and C Extensions</strong>: Pandas uses Cython and C extensions to speed up operations. Critical performance paths are often implemented in C for efficiency, which reduces the overhead associated with pure Python code.</p><p><strong>4. Memory Management</strong></p><p><strong>Memory Efficiency</strong>: Pandas uses efficient data types and memory management techniques to minimize the memory footprint. For example, categorical data types help to efficiently manage columns with repetitive string values.</p><p><strong>Chunking and Lazy Evaluation</strong>: For very large datasets, Pandas can read data in chunks, process them incrementally, and use lazy evaluation to avoid loading the entire dataset into memory at once.</p><p><strong>5. Optimized I/O Operations</strong></p><p><strong>Efficient I/O Operations</strong>: Pandas provides optimized methods for reading and writing data to various file formats (e.g., CSV, Excel, HDF5). The use of efficient parsing and serialization techniques ensures that I/O operations are fast</p><p><strong>6. Parallel Processing</strong></p><p><strong>Parallelism</strong>: While Pandas itself is not inherently parallel, it can be used in conjunction with parallel processing libraries like Dask to handle larger-than-memory computations by parallelizing operations across multiple cores or machines.</p><blockquote><strong>When Not to Use Pandas</strong></blockquote><p>While Pandas is a versatile tool, there are scenarios where it might not be the best choice:</p><ol><li><strong>Extremely Large Datasets</strong>: Pandas operates primarily in-memory, meaning it loads the entire dataset into memory. For extremely large datasets that exceed your system’s memory, using distributed computing frameworks like <strong>Dask</strong> or <strong>Apache Spark</strong> might be more appropriate.</li><li><strong>Real-Time Data Processing</strong>: Pandas is designed for batch processing rather than real-time data streams. For real-time data engineering, tools like <strong>Apache Kafka</strong> or <strong>Apache Flink</strong> are better suited.</li><li><strong>Complex, Multi-Step ETL Pipelines</strong>: While Pandas can handle ETL (Extract, Transform, Load) tasks, building and maintaining complex, production-level ETL pipelines might be more manageable with specialized tools like <strong>Apache Airflow</strong> or <strong>Luigi</strong>.</li></ol><p>Pandas is a powerful and flexible library that has become an indispensable tool in the data engineer’s toolkit. It enables efficient data manipulation and analysis, making it ideal for a wide range of data engineering tasks. However, understanding when to leverage Pandas and when to opt for other tools is key to building efficient and scalable data engineering workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed17fa3bac1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>