pandas Explained: Series and DataFrame
After completing this topic, you will be able to:
- Explain what Series and DataFrame are in pandas.
- Load a CSV file and perform basic operations.
What is pandas?
pandas is a library for working with tabular data in Python. Think of it as a way to manipulate spreadsheets like Excel, but with code.
import pandas as pd
# Read a CSV file β it's as simple as thisdf = pd.read_csv("students.csv")print(df)Name Age Score
0 Kim 25 85
1 Lee 23 92
2 Park 27 78pd is the conventional abbreviation for pandas. You'll almost always see it used in data analysis code.
Series: A One-Dimensional Data Structure
A Series is a labeled, one-dimensional array. A column in a DataFrame is a Series.
import pandas as pd
# Create a Seriesscores = pd.Series([85, 92, 78], index=["Kim", "Lee", "Park"])print(scores)Kim 85
Lee 92
Park 78
dtype: int64# Access by indexprint(scores["Lee"]) # 92
# Conditional filteringprint(scores[scores >= 80])# Kim 85# Lee 92
# Operationsprint(scores.mean()) # 85.0print(scores.max()) # 92It's similar to a list, but you can access elements by name, and it has built-in statistical methods.
DataFrame: The Whole Table
A DataFrame is a two-dimensional table composed of multiple Series. It has rows and columns.
import pandas as pd
# Create from a dictionarydata = { "Name": ["Kim", "Lee", "Park"], "Age": [25, 23, 27], "Score": [85, 92, 78]}df = pd.DataFrame(data)print(df)Name Age Score
0 Kim 25 85
1 Lee 23 92
2 Park 27 78Basic Operations
# Select a columnprint(df["Name"]) # Returns a Seriesprint(df[["Name", "Score"]]) # Returns a DataFrame
# Select a rowprint(df.loc[0]) # Row 0 (by label)print(df.iloc[0]) # Row 0 (by position)
# Conditional filteringhigh = df[df["Score"] >= 80]print(high)# Name Age Score# 0 Kim 25 85# 1 Lee 23 92
# Basic statisticsprint(df.describe())# Mean, standard deviation, min/max, etc., for Age and ScoreCommonly Used Methods
df.head(3) # First 3 rowsdf.tail(3) # Last 3 rowsdf.shape # (Number of rows, number of columns) - e.g., (3, 3)df.columns # List of column namesdf.dtypes # Data type of each columndf.info() # Summary information (including missing values)df.sort_values("Score", ascending=False) # Sort by Score in descending orderAdding and Deleting Columns
# Add a new columndf["Passed"] = df["Score"] >= 80print(df)# Name Age Score Passed# 0 Kim 25 85 True# 1 Lee 23 92 True# 2 Park 27 78 False
# Delete a columndf = df.drop("Passed", axis=1)# axis=0 is for rows, axis=1 is for columnsWhy pandas?
| Task | Pure Python | pandas |
|---|---|---|
| Read CSV | 10+ lines (open, split, loop) | pd.read_csv() 1 line |
| Calculate mean | Calculate sum()/len() directly | df.mean() |
| Conditional filtering | for + if | df[df["column"] > value] |
| Sorting | sorted() + key | df.sort_values() |
Not only is the code shorter, but pandas is internally optimized with C/Cython, making it 10 to 100 times faster than pure Python.