Python for Data & Web
Python Pandas Basics
pandas is Python's go-to library for working with tabular data — think spreadsheets and CSV files, but with powerful code-based tools to explore, clean, and filter that data.
Series and DataFrame
pandas has two core data structures. A Series is a single labelled column of data, like a list with an index attached. A DataFrame is a full table made of multiple Series, with rows and named columns, similar to an Excel sheet or SQL table.
pip install pandasimport pandas as pd
ages = pd.Series([21, 24, 19], name="age")
print(ages)
data = {"name": ["Aarav", "Diya", "Kabir"], "age": [21, 24, 19]}
df = pd.DataFrame(data)
print(df)Reading a CSV File
Real-world data usually comes from CSV files. pandas read_csv() loads a file straight into a DataFrame in one line, ready for exploration.
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head())
print(df.info())head() shows the first five rows by default, useful for a quick peek at your data, while info() prints column names, data types, and how many non-missing values each column has — a great first check on any new dataset.
Selecting Columns and Filtering Rows
You select a single column using square brackets with the column name, which returns a Series. To filter rows based on a condition, place a boolean expression inside the brackets — pandas keeps only the rows where it evaluates to True.
import pandas as pd
df = pd.read_csv("students.csv")
names = df["name"]
print(names)
adults = df[df["age"] >= 21]
print(adults)Chain conditions with & (and) or | (or), and wrap each condition in parentheses, e.g. df[(df["age"] > 20) & (df["city"] == "Pune")].
| Method | Purpose |
|---|---|
| pd.read_csv() | Load a CSV file into a DataFrame |
| .head() | Preview first rows |
| .info() | Column types and missing values |
| df["col"] | Select one column |
| df[condition] | Filter rows by a condition |
