Creating DataFrames
A DataFrame can be built from dictionaries, lists of records, NumPy arrays or files.
In this page:
Syntax
df = pd.DataFrame({"column1": [v1, v2], "column2": [v3, v4]})
df = pd.DataFrame([{"column1": v1, "column2": v2}, {"column1": v3, "column2": v4}])
Creating DataFrames
The most common ways are a dict of columns, a list of dicts (one per row), or a 2-D array with column names. The columns argument selects and orders columns, and index sets the row labels. Reading files with read_csv is the usual real-world route.
Note:
A list of dicts is a natural shape for JSON API responses.
Example: Creating DataFrames
import pandas as pd
import numpy as np
a = pd.DataFrame({"x": [1, 2], "y": [3, 4]})
b = pd.DataFrame([{"x": 1, "y": 3}, {"x": 2, "y": 4}])
c = pd.DataFrame(np.array([[1, 3], [2, 4]]), columns=["x", "y"])
print(a.equals(b), a.equals(c))
print(a)
# Output:
# True True
# x y
# 0 1 3
# 1 2 4
Related Topics
Common Mistakes
- Mixing up dict-of-lists with list-of-dicts shapes
- Lists of unequal length in a dict
- Forgetting to name the columns for arrays
Chapter Summary
- Dict of columns is the common form
- A list of dicts gives one dict per row
- Arrays need column names
- index sets row labels
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: