Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Working with Pandas: A Beginner Guide

1 min read .
Working with Pandas: A Beginner Guide

Pandas is a widely used Python library for tabular data manipulation and analysis. This guide covers a few everyday DataFrame operations: renaming columns, adding and updating rows, deleting data, sorting, and filtering.

Install Pandas

python -m pip install pandas

Create a DataFrame

import pandas as pd

df = pd.DataFrame(
    {
        "Name": [
            "Braund, Mr. Owen Harris",
            "Allen, Mr. William Henry",
            "Bonnell, Miss. Elizabeth",
        ],
        "Age": [22, 35, 58],
        "Sex": ["male", "male", "female"],
    }
)

Rename a Column

df = df.rename(columns={"Sex": "Gender"})

Returning a new DataFrame instead of relying on inplace=True often makes transformation pipelines easier to reason about.

Add a Row

For a small interactive example, assigning through .loc is convenient:

df.loc[len(df)] = ["Smith, Mr. John", 28, "male"]

When adding many rows, build a DataFrame for the new records and combine it once with pd.concat() instead of repeatedly appending one row at a time.

Update Data

Use .loc with a boolean condition:

df.loc[df["Name"] == "Allen, Mr. William Henry", "Age"] = 36

Delete Rows or Columns

Remove rows by condition:

df = df[df["Name"] != "Allen, Mr. William Henry"]

Remove a row by index:

df = df.drop(index=3)

Only do this when index 3 actually exists.

Remove a column:

df = df.drop(columns=["Age"])

Sort Data

Ascending:

sorted_ascending = df.sort_values(by="Age")

Descending:

sorted_descending = df.sort_values(by="Age", ascending=False)

sort_values() returns a new DataFrame by default.

Filter Data

Rows where age is below 30:

below_30 = df[df["Age"] < 30]

Rows where age equals 35:

age_35 = df[df["Age"] == 35]

For multiple conditions, wrap each expression in parentheses:

result = df[(df["Age"] >= 30) & (df["Gender"] == "female")]

Conclusion

Pandas provides concise tools for common data-cleaning and transformation tasks. Once you are comfortable with column selection, .loc, boolean masks, drop(), and sort_values(), you have the foundation for more advanced grouping, joins, aggregation, and time-series analysis.

Related Posts

chevron-up