Sub topic 1
A DataFrame is typed columns sharing an index
A pandas DataFrame looks like a spreadsheet, but it is not stored as a grid of cells. It is stored as a set of columns. Each column is an array that holds one kind of value, and all columns share one row index. This model explains most of what you will see later in this tutorial: why a column can change type when it gets a missing value, why string columns use a lot of memory, and why row operations behave differently from column operations.
This chapter builds that working model and shows how to inspect it.
Prerequisites
This chapter assumes you can:
- Create a DataFrame from a dictionary and select a column with
df["name"]. - Recognize the basic Python types
int,float, andstr. - Read short pandas output such as
df.head()anddf.dtypes.
Knowing NumPy arrays helps but is not required. This chapter introduces the one idea you need: a NumPy array holds values of a single type.
The examples target pandas 2.x. Where pandas 3 behaves differently, the text says so.
The working model
A DataFrame has three parts:
- Row index. A single
Indexobject that labels the rows. Every column uses it. - Column labels. A second
Indexobject that holds the column names. - Columns. One array per column. Each array has exactly one dtype, the data type that applies to every value in that column.
A dtype (data type) tells pandas how to interpret and store the values of an array. For example, int64 means 64-bit signed integers and float64 means 64-bit floating-point numbers.
The dashed lines show that the row index labels the positions of every column. The columns do not store their own labels. They store values, and the index gives each position a name.
Each column has its own dtype
The first example creates a DataFrame with three kinds of data and prints the dtype of each column.
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [1.5, 2.5, 3.5],
"c": ["x", "y", "z"],
})
print(df.dtypes)You should see int64 for a, float64 for b, and object for c. Three things to notice:
df.dtypesis itself aSeries. Its index is the column labels and its values are the dtypes.- Column
aholds integers and columnbholds floats. The two types are not mixed or converted to a common type. A spreadsheet has no equivalent of this. - Strings appear as
objectin pandas 2.x. Theobjectdtype means "an array of pointers to Python objects", and a later chapter covers its cost. Pandas 3 infers a dedicated string dtype by default, so the same column prints asstrthere.
Columns are Series that share the index
Selecting one column returns a Series. A Series is a one-dimensional array with a dtype and an index. When you select a column from a DataFrame, the Series has the same index as the DataFrame.
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3], "b": [1.5, 2.5, 3.5], "c": ["x", "y", "z"]},
index=["r1", "r2", "r3"],
)
col = df["a"]
print(type(col).__name__) # Series
print(col.index.equals(df.index)) # True
print(col.dtype) # int64
print(type(col.to_numpy()).__name__) # ndarray
print(df.shape) # (3, 3)
print(list(df.columns)) # ['a', 'b', 'c']to_numpy() returns the values of the column as a NumPy array. For a plain int64 or float64 column this array holds the numbers directly in one block of memory.
The following table lists the attributes you will use most when you inspect this structure.
| Attribute | Returns | What it tells you |
|---|---|---|
| `df.index` | `Index` | Row labels, shared by all columns |
| `df.columns` | `Index` | Column labels |
| `df.dtypes` | `Series` | One dtype per column, indexed by column label |
| `df["a"].dtype` | dtype | The dtype of a single column |
| `df.shape` | tuple | `(number of rows, number of columns)` |
| `df.info()` | printed summary | Dtypes, non-null counts, and approximate memory |
Mixing up df.dtypes (plural, a Series for the whole frame) and Series.dtype (singular, one dtype) is a common source of AttributeError. A Series has only .dtype. A DataFrame has only .dtypes.
The dtype belongs to the column, not the row
Because storage is organized by column, a single row does not have its own storage. When you ask for a row, pandas builds a new Series by taking one value from each column. That Series needs a single dtype, so pandas finds a type that fits all the values.
import pandas as pd
df = pd.DataFrame(
{"a": [1, 2, 3], "b": [1.5, 2.5, 3.5], "c": ["x", "y", "z"]},
index=["r1", "r2", "r3"],
)
print(df.loc["r1"].dtype) # object
print(df[["a", "b"]].loc["r1"].dtype) # float64
print(df[["a"]].loc["r1"].dtype) # int64The results follow a pattern:
- A row that mixes numbers and strings becomes
object, because onlyobjectcan hold both. - A row that mixes an integer and a float becomes
float64. The integer1turns into1.0. - A row from integer-only columns stays
int64.
This has two practical effects. First, row-by-row loops such as iterrows() can silently change types, and they copy data for every row. Second, column operations such as df["a"].sum() work directly on one array, which is why they are fast. When you have a choice, prefer working column by column.
Alignment: the index is part of the data
Because every column shares an index, pandas uses index labels, not positions, when it combines data. This is called alignment.
import pandas as pd
s1 = pd.Series([1, 2, 3], index=["x", "y", "z"])
s2 = pd.Series([10, 20, 30], index=["y", "z", "w"])
total = s1 + s2
print(total)
print(total.dtype)The result has the union of both indexes: w, x, y, z. Only y and z appear in both inputs, so those are 12.0 and 23.0. The labels x and w each appear in only one input, so their results are NaN, which stands for "not a number" and marks a missing value.
Look at the dtype. Both inputs were int64, but the result is float64. Integer arrays in NumPy have no way to represent a missing value, so pandas converts the result to float to make room for NaN. The next chapters in this tutorial explain this promotion in detail. For now, remember that the index can create missing values even when your input data has none.
Assigning a Series as a new column also aligns on the index:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]}, index=["r1", "r2", "r3"])
extra = pd.Series([100, 200], index=["r3", "r1"])
df["d"] = extra
print(df)
print(df.dtypes)Pandas matches r1 to 100... more precisely, r1 gets 200 and r3 gets 100, regardless of the order in extra. Row r2 has no match and gets NaN, so column d is float64. If you assign a plain list or NumPy array instead of a Series, pandas skips alignment and matches by position. The length must then equal the number of rows, or pandas raises a ValueError.
Changing the dtype of a column
You change a dtype one column at a time. astype returns a new object and leaves the original unchanged, so you assign the result back.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [1.5, 2.5, 3.5]})
df["a"] = df["a"].astype("float64")
df = df.astype({"b": "float32"})
print(df.dtypes)The first line replaces the whole column a with a new array. Assigning to a whole column can give it any dtype, because pandas swaps the array and does not write into the old one.
Writing a single value is different, because the existing array keeps its dtype. If you write the float 1.5 into an int64 column with df.loc[0, "a"] = 1.5, pandas 2.x upcasts the column to float64 and emits a FutureWarning that this behavior is deprecated. The pandas deprecation notes say a future release will raise an error instead. To stay safe, convert the column to the dtype you need first, then assign.
Selecting columns by dtype
Since dtype is a column property, you can select columns by it. select_dtypes filters the columns and keeps the index.
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [1.5, 2.5, 3.5],
"c": ["x", "y", "z"],
})
numeric = df.select_dtypes(include="number")
other = df.select_dtypes(exclude="number")
print(list(numeric.columns)) # ['a', 'b']
print(list(other.columns)) # ['c']This is useful before an operation that only makes sense for numbers, such as df.corr() or a mean across columns.
Common errors
These mistakes come from forgetting that data is stored as typed columns with a shared index.
- Expecting a row to keep column dtypes. A row from mixed columns is
objectorfloat64. If you need the original types, select the column first and then the row. - Assuming a string column shows
str. In pandas 2.x the dtype isobject. Code that testsdtype == "str"fails there, so usepd.api.types.is_string_dtypefor a version-independent check. - Duplicate column names. If two columns share a label,
df["a"]returns a DataFrame with both columns, not a Series. Code that then calls.dtypefails. - Duplicate index labels in alignment. Alignment between two objects with repeated labels can multiply rows or raise an error. Check
df.index.is_uniquewhen a result has more rows than expected. - Unexpected float columns. An integer column turned into
float64almost always means a missing value entered through alignment, a merge, or a reindex. Look at where a label had no match. - Reading
df.dtypesonce and trusting it. Dtypes can change after a merge, a concatenation, or a reassignment. Print them again after each step that could introduce missing values.
Putting the model to work
With this model you can read a DataFrame's behavior directly from its structure. Ask these questions about any frame:
- What is the dtype of each column? Check
df.dtypes. - Is the index unique, and do the objects I combine share it?
- Which operation touches whole columns, and which builds rows by combining types?
The later chapters of this tutorial take each part of this picture further. They look at what each dtype stores, how pandas groups same-dtype columns into blocks, and how to measure and reduce memory. Each of them depends on the idea from this chapter: a DataFrame is a set of typed columns that share an index.
Exercise
You have a DataFrame with an integer column qty and a float column price. You call df.loc[0] and print its dtype. What dtype do you expect, and why? What changes if the frame also has a string column?
Show answer
Expect float64. A row is built as one Series, so pandas picks a single dtype that fits all its values, and the integer from qty converts to a float to match price. If the frame also has a string column, the row becomes object, because only object can hold numbers and strings together.
Exercise
s1 = pd.Series([1, 2, 3], index=["a", "b", "c"]) and s2 = pd.Series([4, 5, 6], index=["b", "c", "d"]). What are the index and the dtype of s1 + s2, and which labels hold NaN?
Show answer
The index is the union a, b, c, d. Labels a and d exist in only one input, so they hold NaN. Labels b and c hold 6.0 and 8.0. The dtype is float64, because an int64 array cannot hold NaN, so pandas converts the result to float.