Data Structures in Pandas

Pandas is built around two core data structures: the Series, a one-dimensional labeled array, and the DataFrame, a two-dimensional labeled table made up of multiple Series stacked together as columns.

The Series

A Series holds a single column of data, along with an index that labels each value - similar to a single column in a spreadsheet.

import pandas as pd

scores = pd.Series([85, 92, 78], index=["Abhay", "Priya", "Rohit"])
print(scores)
# Abhay    85
# Priya    92
# Rohit    78
# dtype: int64

print(scores["Priya"])   # 92 - access by label

The DataFrame

A DataFrame is a two-dimensional table made up of rows and columns, where each column is technically a Series. It's the primary structure you'll work with for almost all real data analysis in Pandas.

import pandas as pd

data = {
    "Name": ["Abhay", "Priya", "Rohit"],
    "Course": ["Data Science", "Data Science", "Data Science"],
    "Score": [85, 92, 78]
}

df = pd.DataFrame(data)
print(df)
print(type(df["Score"]))   # <class 'pandas.core.series.Series'> - each column is a Series

Creating a DataFrame from Other Sources

import pandas as pd

# From a list of lists
df2 = pd.DataFrame([[1, "A"], [2, "B"]], columns=["ID", "Grade"])

# From a list of dictionaries
df3 = pd.DataFrame([{"a": 1, "b": 2}, {"a": 3, "b": 4}])
Think of it this way: a Series is a single labeled column, and a DataFrame is a collection of Series sharing the same index - understanding this relationship makes almost every other Pandas operation easier to reason about.

You've Completed This Section

You now understand the two building blocks of Pandas - the Series and the DataFrame - and how they work together to represent real-world tabular data. This sets you up perfectly for the hands-on data manipulation techniques covered next in the full course.

The Index: The Quiet Third Structure

Both a Series and a DataFrame carry an Index object, and it is more than a row label. Pandas uses it to align data. When you add two Series, values are matched by label, not by position.

import pandas as pd

maths   = pd.Series([80, 90, 70], index=["Asha", "Ravi", "Meena"])
science = pd.Series([85, 75], index=["Ravi", "Asha"])

print(maths + science)
# Asha     155.0
# Meena      NaN
# Ravi     165.0
# dtype: float64

Meena has no science score, so the result is NaN (missing). Notice the dtype also changed to float, because integers cannot hold NaN in a standard integer column. Alignment prevents silent mismatches, but it surprises beginners who expect position-based addition.

Inspecting and Selecting Data

A few attributes and methods tell you almost everything about a DataFrame's structure:

df = pd.DataFrame({
    "city": ["Delhi", "Pune", "Jaipur", "Kochi"],
    "temp": [31.5, 27.0, 34.2, 29.8],
    "rain_mm": [0, 12, 0, 40],
})

print(df.shape)       # (4, 3)  rows, columns
print(df.dtypes)      # data type of each column
df.info()             # columns, non-null counts, memory
print(df.describe())  # quick statistics for numeric columns

df["temp"]            # one column      -> Series
df[["city", "temp"]]  # list of columns -> DataFrame
df.loc[1, "city"]     # by label        -> 'Pune'
df.iloc[0:2]          # by position     -> first two rows
df[df["rain_mm"] > 0] # boolean filter  -> rainy cities

The single versus double square bracket rule matters: one column name gives a Series, a list of names gives a DataFrame, even if the list has only one item.

loc vs iloc

loc works with labels and includes the end of a slice. iloc works with integer positions and excludes the end, just like Python lists. Choosing the wrong one is a common source of off-by-one errors.

Converting Between the Structures

Real analysis often moves data back and forth between shapes. A grouped calculation may return a Series that you want as a table, or an API may need plain Python objects. These conversions are cheap and common:

  • series.to_frame() turns a Series into a one-column DataFrame.
  • df.set_index("city") moves a column into the index; reset_index() moves it back.
  • df.to_dict("records") gives a list of dictionaries, handy for sending data to an API.
  • df["temp"].to_numpy() returns a NumPy array for numeric work.

Common Mistakes with DataFrames

  • Chained assignment such as df[df.temp > 30]["rain_mm"] = 5 may change a temporary copy instead of df. Use df.loc[df.temp > 30, "rain_mm"] = 5.
  • Forgetting copies. When you slice a DataFrame and plan to modify the slice, call .copy() to make an independent object.
  • Numbers stored as text. Values read from CSV files may arrive as object dtype; convert with pd.to_numeric.
  • Mixed types in one column. A Series holds one dtype; mixing numbers and strings forces object, which is slower and breaks maths operations.
  • Duplicate index labels make loc return several rows when you expected one. Check with df.index.is_unique.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course