Search Knowledge

© 2026 LIBREUNI PROJECT

Python for Scientific Computing / Pandas Deep Dive

Pandas: Data Cleaning and Wrangling

The Reality of Data

In textbooks, data is clean. In reality, data is missing, duplicated, inconsistent, and scattered across multiple files. Data scientists spend roughly 80% of their time cleaning and wrangling data. Pandas is designed to make this “grunt work” efficient.

Duplicates and Noise

Common cleaning tasks include removing duplicate rows and inconsistent strings.

python
1 
2import pandas as pd
3 
4df = pd.DataFrame({
5 'k1': ['one', 'two'] * 3 + ['two'],
6 'k2': [1, 1, 2, 3, 3, 4, 4]
7})
8 
9print("Original DF:\n", df)
10 
11# Identify duplicates
12print("\nIs Duplicate:\n", df.duplicated())
13 
14# Remove duplicates
15print("\nCleaned DF:\n", df.drop_duplicates())
16 

Transforming Data: map and apply

Sometimes you need to apply a custom function to every element or row in a DataFrame.

  • map(): Used on a Series to substitute values based on a dictionary or function.
  • apply(): Used on a DataFrame to apply a function along an axis (rows or columns).
python
1 
2import pandas as pd
3 
4df = pd.DataFrame({
5 'food': ['bacon', 'pulled pork', 'bacon', 'Pastrami', 'corned beef'],
6 'ounces': [4, 3, 12, 6, 7.5]
7})
8 
9# Mapping food to animal source
10meat_to_animal = {
11 'bacon': 'pig',
12 'pulled pork': 'pig',
13 'pastrami': 'cow',
14 'corned beef': 'cow'
15}
16 
17# Normalize string and map
18df['animal'] = df['food'].str.lower().map(meat_to_animal)
19print("Transformation results:\n", df)
20 

Combining Datasets: Merge, Join, and Concatenate

In a relational database model, data is split across tables. Pandas allows you to bring them together.

Merge (SQL Join)

Merge connects rows in DataFrames based on one or more keys.

python
1 
2import pandas as pd
3 
4df1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
5df2 = pd.DataFrame({'key': ['a', 'b', 'd'], 'data2': range(3)})
6 
7# Inner Join (default)
8merged = pd.merge(df1, df2, on='key')
9print("Merged Data (Inner):\n", merged)
10 
11# Outer Join
12outer = pd.merge(df1, df2, on='key', how='outer')
13print("\nMerged Data (Outer):\n", outer)
14 

Concatenate

Concatenate “stacks” DataFrames on top of each other or side-by-side.

python
1 
2import pandas as pd
3import numpy as np
4 
5s1 = pd.Series([0, 1], index=['a', 'b'])
6s2 = pd.Series([2, 3, 4], index=['c', 'd', 'e'])
7 
8print("Concatenated Series:\n", pd.concat([s1, s2]))
9 

Reshaping and Pivoting

Changing the layout of a DataFrame (Long to Wide format or vice versa) is essential for visualization and certain machine learning models.

python
1 
2import pandas as pd
3 
4df = pd.DataFrame({
5 'date': ['2021-01-01', '2021-01-01', '2021-01-02'],
6 'variable': ['temp', 'humidity', 'temp'],
7 'value': [22.5, 60, 23.0]
8})
9 
10# Pivot to wide format
11pivoted = df.pivot(index='date', columns='variable', values='value')
12print("Pivoted (Wide) Data:\n", pivoted)
13 

Advanced String Manipulation

Pandas provides a .str accessor for performing vectorized string operations.

python
1 
2import pandas as pd
3 
4names = pd.Series([' Alice ', 'bOB', ' Charlie ', 'd_avid'])
5 
6# Strip whitespace and capitalize
7clean_names = names.str.strip().str.capitalize()
8print("Clean names:\n", clean_names)
9 
10# Regex operations
11print("\nContains 'a'?", clean_names.str.contains('a'))
12 

In the next module, we’ll dive into Time-Series analysis, one of Pandas’ strongest features.