<jupyter_start><jupyter_text>All the IPython Notebooks in this lecture series by Dr. <NAME> are available @ **[GitHub](https://github.com/milaan9/10_Python_Pandas_Module/tree/main/001_Python_Pandas_Methods)**  Drop duplicates in pandas DataFrameIn this class, we learn to remove duplicates from the **[Pandas DataFrame](https://github.com/milaan9/10_Python_Pandas_Module/blob/main/001_Python_Pandas_DataFrame.ipynb)**.Data is gathered from various sources. It may not be in the proper form. It contains garbage values and duplicate data. Before analyzing a dataset, it must be clean and precise. Also, See:* **[Drop columns in pandas DataFrame](https://github.com/milaan9/10_Python_Pandas_Module/blob/main/001_Python_Pandas_Methods/004_Python_Pandas_DataFrame_drop_columns.ipynb)*** **[Drop columns with NA in pandas DataFrame](https://github.com/milaan9/10_Python_Pandas_Module/blob/main/001_Python_Pandas_Methods/006_Python_Pandas_DataFrame_drop_columns_with_NA.ipynb)**  The `DataFrame.drop_duplicates()` functionThis function is used to remove the duplicate rows from a DataFrame.**Syntax:**```pythonDataFrame.drop_duplicates(subset=None, keep='first', inplace=False, ignore_index=False)```**Parameters:**1. **`subset`**: By default, if the rows have the same values in all the columns, they are considered duplicates. This parameter is used to specify the columns that only need to be considered for identifying duplicates.2. **`keep`**: Determines which duplicates (if any) to keep. It takes inputs as,    * **first** – Drop duplicates except for the first occurrence. This is the default behavior.    * **last** – Drop duplicates except for the last occurrence.    * **False** – Drop all duplicates.3. **`inplace`**: It is used to specify whether to return a new DataFrame or update an existing one. It is a boolean flag with default False.4. **`ignore_index`**: It is a boolean flag to indicate if row index should be reset after dropping duplicate rows. **`False`**: It keeps the original row index. **`True`**: It reset the index, and the resulting rows will be labeled 0, 1, …, n – 1.**Returns:*** It returns the DataFrame with dropped columns or None if **`inplace=True`**  Drop duplicates but keep firstWhen we have the DataFrame with many duplicate rows that we want to remove we use **`DataFrame.drop_duplicates()`**.The rows that contain the same values in all the columns then are identified as duplicates. If the row is duplicated then by default **`DataFrame.drop_duplicates()`** keeps the first occurrence of that row and drops all other duplicates of it.**Example:**<jupyter_code>import pandas as pd

student_dict = {"name": ["Joe", "Nat", "Harry", "Joe", "Nat"], "age": [20, 21, 19, 20, 21],
                "marks": [85.10, 77.80, 91.54, 85.10, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print("Before dropping duplicates: \n", student_df)

# drop duplicate rows
student_df = student_df.drop_duplicates()

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54
3    Joe   20  85.10
4    Nat   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54<jupyter_text>Drop duplicates from defined columnsBy default, **`DataFrame.drop_duplicate()`** removes rows with the same values in all the columns. But, we can modify this behavior using a subset parameter.For example, **`subset=[col1, col2]`** will remove the duplicate rows with the same values in specified columns only, i.e., **`col1`** and **`col2`**.**Example:**In the below example, rows for **`Nat`** and **`Sam`** are removed even though their names are different because only **`age`** and **`marks`** columns are considered to check for duplicates.<jupyter_code>import pandas as pd

student_dict = {"name":["Joe","Nat","Harry","Sam" ], "age":[20,21,19,21], "marks":[85.10, 77.80, 91.54, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print("Before dropping duplicates: \n", student_df)

# drop duplicate rows
student_df = student_df.drop_duplicates(subset=['age','marks'])

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54
3    Sam   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54<jupyter_text>Drop duplicates but keep lastLet’s consider the case where we have a row that is duplicated multiple times in the DataSet. In such a case, To keep only one occurrence of the duplicate row, we can use the **`keep`** parameter of a **`DataFrame.drop_duplicate()`**, which takes the following inputs:* **first** – Drop duplicates except for the first occurrence of the duplicate row. This is the default behavior.* **last** – Drop duplicates except for the last occurrence of the duplicate row.* **False** – Drop all the rows which are duplicate.**Example:**In the below example, we are dropping the last occurrence of the duplicate rows using **`keep='last'`**.<jupyter_code>import pandas as pd

student_dict = {"name": ["Joe", "Nat", "Harry", "Nat"], "age": [20, 21, 19, 21], "marks": [85.10, 77.80, 91.54, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print("Before dropping duplicates: \n", student_df)

# drop duplicate rows
student_df = student_df.drop_duplicates(keep='last')

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54
3    Nat   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
2  Harry   19  91.54
3    Nat   21  77.80<jupyter_text>Drop all duplicatesAs explained in the above section, by default, **`DataFrame.drop_duplicates()`** keeps the duplicate row’s first occurrence and removes all others.If we need to drop all the duplicate rows, then it can be done by using keep=False, as shown below.<jupyter_code>import pandas as pd

student_dict = {"name": ["Joe", "Nat", "Harry", "Nat"], "age": [20, 21, 19, 21], "marks": [85.10, 77.80, 91.54, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print("Before dropping duplicates: \n", student_df)

# drop all duplicate rows
student_df = student_df.drop_duplicates(keep=False)

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54
3    Nat   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
2  Harry   19  91.54<jupyter_text>Drop duplicates in placeBy default, **`DataFrame.drop_duplicates()`** removes the duplicates and returns the copy of the DataFrame.But, if we want to make changes in the existing DataFrame, then set the flag **`inplace=True`**. It can be used when the drop operation is part of the function chaining.<jupyter_code>import pandas as pd

student_dict = {"name": ["Joe", "Nat", "Harry", "Joe", "Nat"], "age": [20, 21, 19, 20, 21],
                "marks": [85.10, 77.80, 91.54, 85.10, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict)
print("Before dropping duplicates: \n", student_df)

# drop duplicate rows
student_df.drop_duplicates(inplace=True)

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54
3    Joe   20  85.10
4    Nat   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
1    Nat   21  77.80
2  Harry   19  91.54<jupyter_text>Drop duplicates and reset the indexWhen we drop the rows from DataFrame, by default, it keeps the original row index as is. But, if we need to reset the index of the resultant DataFrame, we can do that using the **`ignore_index`** parameter of **`DataFrame.drop_duplicate()`**.* If **`ignore_index=True`**, it reset the row labels of resultant DataFrame to 0, 1, …, n – 1.* If **`ignore_index=False`** it does not change the original row index. By default, it is **False**.<jupyter_code>import pandas as pd

student_dict = {"name": ["Joe", "Nat", "Harry", "Nat"], "age": [20, 21, 19, 21], "marks": [85.10, 77.80, 91.54, 77.80]}

# Create DataFrame from dict
student_df = pd.DataFrame(student_dict, index=['a', 'b', 'c', 'd'])
print("Before dropping duplicates: \n", student_df)

# drop duplicate rows
student_df = student_df.drop_duplicates(keep=False, ignore_index=True)

print("\nAfter dropping column: \n", student_df)<jupyter_output>Before dropping duplicates: 
     name  age  marks
a    Joe   20  85.10
b    Nat   21  77.80
c  Harry   19  91.54
d    Nat   21  77.80

After dropping column: 
     name  age  marks
0    Joe   20  85.10
1  Harry   19  91.54
{'fraction_non_alphanumeric': 0.11138365481101573, 'fraction_numerical': 0.054632623480878585, 'mean_word_length': 4.161104718066744, 'pattern_counts': {'":': 18, '<': 20, '<?xml version=': 0, '>': 20, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '242688', 'license': 'MIT', 'n_tokens_mistral': 3202, 'n_tokens_neox': 2773, 'n_words': 1114, 'path': '001_Python_Pandas_Methods/005_Python_Pandas_DataFrame_drop_duplicates.ipynb', 'repo_name': 'milaan9/10_Python_Pandas_Module', 'size': '8975'}