Learn Pandas · 6/14

Manipulating Columns and Data Types

7 min read

🐼 Manipulating Columns and Data Types in Pandas

Welcome back to the wonderful world of Pandas! So, you've loaded your data, and it's sitting there in a DataFrame, looking all neat and tidy. But is it really ready for analysis? Often, the raw data we get is like a lump of clay – it has potential, but you need to shape it. This guide will walk you through the essential skills of molding your data by manipulating columns and fixing data types. Think of yourself as a data sculptor! 🗿


1. Creating New Columns: Feature Engineering Basics 🛠️

The Problem: Your current dataset is good, but it's missing a key piece of information that you have to derive from the existing data. For instance, you might have the price and quantity of items sold, but you really need the total_revenue.

The Solution: You can create a new column that is a result of operations on other columns. This is a fundamental concept in feature engineering, which is a fancy term for creating new 'features' (columns) from existing ones to improve your analysis or machine learning models.

Let's imagine we have a dataset of a fruit stand's sales.

python
import pandas as pd

# Sample sales data
data = {'fruit': ['apple', 'banana', 'cherry', 'date'],
        'price_per_item': [0.5, 0.25, 1.0, 0.75],
        'quantity_sold': [100, 150, 50, 75]}
df = pd.DataFrame(data)

print("Original DataFrame:")
print(df)

Now, to calculate the total_revenue for each fruit, we simply multiply the price_per_item by the quantity_sold.

python
# Creating a new column 'total_revenue'
df['total_revenue'] = df['price_per_item'] * df['quantity_sold']

print("\nDataFrame with new 'total_revenue' column:")
print(df)

What just happened? We created a new column named total_revenue and assigned the result of the multiplication of the two existing columns to it. It's that straightforward! Pandas performs the calculation for each row automatically. This is called a vectorized operation, and it's super-efficient. It's like telling the entire fruit stand crew to calculate their totals at once, rather than going to each one individually.


2. Modifying Existing Columns and Basic Math Operations ✏️

The Problem: Sometimes, a column you have isn't quite right. Maybe you need to update it, perform a mathematical operation on it, or convert its units. For example, what if you decide to give a 10% discount on all fruits? You'd need to update the price_per_item.

The Solution: You can modify an existing column by simply assigning new values to it.

Let's apply that 10% discount. A 10% discount means the new price is 90% of the old price.

python
# Modifying the 'price_per_item' column
df['price_per_item'] = df['price_per_item'] * 0.90

print("DataFrame after applying a 10% discount:")
print(df)

You can also perform other basic math operations like addition (+), subtraction (-), and division (/).

Fun Fact: The ability to perform these operations across entire columns without writing a loop is one of the main reasons Pandas is so popular and powerful. Under the hood, it uses a library called NumPy, which is written in C, making these calculations lightning fast. ⚡


3. Cleaning Up: Dropping Unwanted Columns and Rows 🗑️

The Problem: Your dataset is cluttered with columns or rows that you don't need for your analysis. Maybe there's redundant information, or some rows have missing values that are just getting in the way.

The Solution: The drop() method is your best friend for getting rid of unwanted clutter.

Let's say we have a new dataset with a column that's completely useless.

python
# Sample DataFrame with an unnecessary column
data = {'product_id': [101, 102, 103],
        'product_name': ['Laptop', 'Mouse', 'Keyboard'],
        'useless_info': ['info1', 'info2', 'info3']}
df_clutter = pd.DataFrame(data)

print("Original cluttered DataFrame:")
print(df_clutter)

To drop the useless_info column, we use drop() and specify axis=1 to indicate we're dropping a column.

python
# Dropping the 'useless_info' column
df_cleaned = df_clutter.drop('useless_info', axis=1)

print("\nDataFrame after dropping a column:")
print(df_cleaned)

What if you want to drop a row? Let's say the 'Mouse' entry is incorrect. You can drop it by its index.

python
# Dropping the row with index 1 (the 'Mouse')
df_cleaned_rows = df_cleaned.drop(1, axis=0) # axis=0 for rows

print("\nDataFrame after dropping a row:")
print(df_cleaned_rows)

Heads up! The drop() method by default returns a new DataFrame with the specified columns or rows removed. The original DataFrame remains unchanged. If you want to modify the original DataFrame in place, you can use the inplace=True argument, like so: df_clutter.drop('useless_info', axis=1, inplace=True). However, it's often considered better practice in the industry to create a new DataFrame to avoid unintended side effects.


4. Type Casting: Fixing Data Types with astype() 🎭

The Problem: You load a dataset, and Pandas has incorrectly guessed the data type of a column. For example, a column of numbers might be read as a string (object in Pandas terms), or a date might be just a plain string. This is a big deal because you can't perform mathematical operations on strings!

The Solution: The astype() method lets you change the data type (or "cast") of a column to the correct type.

Imagine a dataset where the price is a string because of a currency symbol.

python
# Sample DataFrame with incorrect data type
data = {'item': ['Pen', 'Pencil', 'Eraser'],
        'price': ['$1.00', '$0.50', '$0.25']}
df_types = pd.DataFrame(data)

print("Original DataFrame with wrong data types:")
print(df_types.dtypes)

First, we need to remove the '$' sign and then we can convert the price column to a numeric type, like float.

python
# First, remove the '$' and then cast to float
df_types['price'] = df_types['price'].str.replace('$', '').astype(float)

print("\nDataFrame with corrected data types:")
print(df_types.dtypes)
print("\n")
print(df_types)

Now you can perform calculations on the price column!

Common Data Types you'll use with astype():

  • int64: For whole numbers.
  • float64: For floating-point numbers (numbers with decimals).
  • 'category': For categorical data (a fixed number of possible values). This can save a lot of memory!
  • 'datetime64[ns]': For dates and times.

5. Custom Logic: Applying Functions with apply() and map() 🧠

The Problem: The operation you need to perform is more complex than a simple mathematical calculation. You might need to apply a custom function to each element, row, or column. For example, you want to categorize your products based on their price into 'cheap', 'medium', and 'expensive'.

The Solution: Pandas provides the flexible apply() and map() methods for these scenarios.

Using apply()

apply() can be used to apply a function along an axis of the DataFrame (either rows or columns).

Let's categorize our fruits from the first example based on their total_revenue.

python
# Let's bring back our fruit stand DataFrame
print("Fruit stand DataFrame:")
print(df)

# Define a function to categorize revenue
def categorize_revenue(revenue):
    if revenue > 50:
        return 'High Revenue'
    elif 20 <= revenue <= 50:
        return 'Medium Revenue'
    else:
        return 'Low Revenue'

# Apply the function to the 'total_revenue' column
df['revenue_category'] = df['total_revenue'].apply(categorize_revenue)

print("\nDataFrame with revenue categories:")
print(df)

Here, apply() took our custom categorize_revenue function and applied it to each value in the total_revenue column.

Using map()

map() is used for substituting each value in a Series with another value. It's great when you have a dictionary mapping old values to new ones.

Imagine you want to translate the fruit names to Spanish.

python
# Dictionary mapping English fruit names to Spanish
fruit_translation = {
    'apple': 'manzana',
    'banana': 'plátano',
    'cherry': 'cereza',
    'date': 'dátil'
}

# Use map() to create a new column with Spanish names
df['fruit_spanish'] = df['fruit'].map(fruit_translation)

print("\nDataFrame with Spanish fruit names:")
print(df)

apply() vs. map(): What's the difference?

  • map() is designed to work on a Series (a single column) and is optimized for mapping values.
  • apply() is more flexible and can work on a Series or be applied to the rows/columns of a DataFrame.

For simple substitutions on a single column, map() is generally faster. For more complex, custom logic, apply() is your go-to.


📚 Extra Reading & References

Challenge

You are given a Pandas DataFrame named sales_df containing raw product sales data. Your task is to clean, transform, and engineer new features in the DataFrame. Perform the following operations in sequence:

  1. The item_price column is currently of object type, containing price strings with a '$' prefix. Clean this column by removing the non-numeric characters and convert its data type to float64.
  2. The quantity_sold column contains erroneous entries represented by -1. Replace all occurrences of -1 in this column with 0.
  3. Create a new column named gross_revenue. This column should be the result of the element-wise multiplication of the cleaned item_price and the corrected quantity_sold columns.
  4. Create a second new column named net_revenue. This column's values should be derived from gross_revenue. For any row where the category is 'Electronics', apply a 10% discount to the gross_revenue. For all other categories, the net_revenue should be equal to the gross_revenue.
  5. Create a third new column named revenue_category. Populate this column by applying a custom function to the net_revenue column. The function should categorize the revenue as 'High' if it is greater than 1000, 'Medium' if it is between 100 and 1000 (inclusive), and 'Low' if it is less than 100.
  6. To finalize the DataFrame, remove the original item_price, quantity_sold, and the intermediate gross_revenue columns.

Assign the final, modified DataFrame to a new variable named cleaned_sales_df.

Expected result

The output should be a Pandas DataFrame assigned to the variable cleaned_sales_df. It must contain four columns: item_id, category, net_revenue, and revenue_category. The original item_price and quantity_sold columns, along with the intermediate gross_revenue column, should be dropped. The data within the DataFrame should reflect all the specified cleaning and transformation steps.

The final DataFrame should look like this:

apache
   item_id     category  net_revenue revenue_category
0      101  Electronics      1080.00             High
1      102        Books        77.50              Low
2      103  Electronics         0.00              Low
3      104   Home Goods       752.25           Medium
4      105        Books        99.90              Low
5      106  Electronics      1350.00             High
6      107   Home Goods        90.00              Low
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.