How to Create a Pandas DataFrame in Python
A Pandas DataFrame is a two-dimensional table with labelled rows and columns. To create a DataFrame in Python, you commonly use pd.DataFrame() and provide data in a form such as a dictionary, a list of dictionaries, a list of lists or a NumPy array. This tutorial explains the most useful methods with practical examples, so you can choose a structure that fits your dataset.
This page focuses on creating a DataFrame. To understand the parts of an existing table—including its index, columns, shape and inspection methods—read the Pandas DataFrame tutorial. If you are just starting with the library, begin with the introduction to Pandas.
- Before you start
- Create a DataFrame from a dictionary of lists
- Create a DataFrame from a list of dictionaries
- Create a DataFrame from a list of lists
- Create a DataFrame with explicit columns
- Create a DataFrame from a NumPy array
- Create a DataFrame from Pandas Series
- Create an empty DataFrame
- Set a custom index
- Add columns after creating a DataFrame
- Create a DataFrame by reading a file
- Which DataFrame creation method should you use?
- Common mistakes
- Practice exercises
- Frequently asked questions
Before You Start: Import Pandas
First, import the Pandas library. The alias pd is the convention used in most tutorials and Python data-analysis projects.
import pandas as pd
If Pandas is not installed in your environment, install it from your terminal or command prompt with python -m pip install pandas. You normally only need to install it once per Python environment.
1. Create a Pandas DataFrame from a Dictionary of Lists
Creating a DataFrame from a dictionary of lists is one of the most common approaches. Each dictionary key becomes a column name, and the list assigned to that key contains the values for that column.
import pandas as pd
data = {
"Product": ["Laptop", "Phone", "Tablet"],
"Units": [3, 5, 4],
"Unit_Price": [800, 500, 300]
}
df = pd.DataFrame(data)
print(df)
Output
Product Units Unit_Price 0 Laptop 3 800 1 Phone 5 500 2 Tablet 4 300
The three keys—Product, Units and Unit_Price—become the DataFrame's columns. Values at the same position in each list form one row. By default, Pandas assigns index labels starting at zero.
ValueError.2. Create a DataFrame from a List of Dictionaries
A list of dictionaries is useful when each dictionary represents one record, such as one student, customer or transaction. The dictionary keys are used as column names.
records = [
{"Name": "Amina", "Age": 20, "Course": "Python"},
{"Name": "Bilal", "Age": 22, "Course": "SQL"},
{"Name": "Sara", "Age": 21, "Course": "Pandas"}
]
df_students = pd.DataFrame(records)
print(df_students)
Output
Name Age Course 0 Amina 20 Python 1 Bilal 22 SQL 2 Sara 21 Pandas
This format often mirrors data received from an API or produced by a program. If some dictionaries omit a key, Pandas creates the corresponding column and fills missing entries with a missing-value marker such as NaN or None, depending on the data and dtype.
records = [
{"Name": "Amina", "Marks": 86},
{"Name": "Bilal", "Marks": 73, "Grade": "B"},
{"Name": "Sara", "Marks": 92, "Grade": "A"}
]
df = pd.DataFrame(records)
print(df)
3. Create a DataFrame from a List of Lists
A list of lists contains row-oriented data. Use the columns argument to assign meaningful labels to each field; otherwise, Pandas uses default integer column labels.
rows = [
["Amina", 86, "A"],
["Bilal", 73, "B"],
["Sara", 92, "A"]
]
df = pd.DataFrame(rows, columns=["Name", "Marks", "Grade"])
print(df)
Output
Name Marks Grade 0 Amina 86 A 1 Bilal 73 B 2 Sara 92 A
This method works well when the data is already arranged by rows, for example when reading values from a small form or building a table from a simple nested list. Make sure each row contains the expected number of values for the supplied column labels.
4. Create a DataFrame with Explicit Columns
You can provide the column names separately using columns=. This is useful when your input data is a list of lists or when you want to control the order and names of the columns.
data = [[101, "North", 1200], [102, "South", 950], [103, "West", 1430]]
df = pd.DataFrame(
data,
columns=["Order_ID", "Region", "Sales"]
)
print(df)
Column order follows the labels supplied in columns. The number of labels should match the number of values in each row. For more control over column selection, renaming and reordering after creation, see the lesson on adding and dropping Pandas columns.
5. Create a DataFrame from a NumPy Array
If your data is stored in a NumPy array, you can pass it directly to pd.DataFrame(). A two-dimensional array maps naturally to rows and columns.
import numpy as np
import pandas as pd
values = np.array([[10, 20], [30, 40], [50, 60]])
df = pd.DataFrame(values, columns=["A", "B"])
print(df)
Output
A B 0 10 20 1 30 40 2 50 60
Arrays generally contain a consistent underlying data type, so mixed-type values may be converted before they reach the DataFrame. If each column needs a different type, check the resulting df.dtypes and convert columns deliberately where needed.
6. Create a DataFrame from Pandas Series
You can combine Series objects into a DataFrame. Pandas aligns their values by index labels, rather than simply assuming that the first item in every Series belongs together.
names = pd.Series(["Amina", "Bilal", "Sara"], index=["S1", "S2", "S3"])
marks = pd.Series([86, 73, 92], index=["S1", "S2", "S3"])
df = pd.DataFrame({"Name": names, "Marks": marks})
print(df)
If the Series have different indexes, Pandas aligns the values using the labels. Labels that are present in one Series but absent from another can produce missing values in the combined DataFrame. This alignment is powerful, but it is important to check indexes when combining real datasets.
Learn more about one-dimensional labelled data in the Pandas Series tutorial.
7. Create an Empty DataFrame
An empty DataFrame can act as a starting structure when you plan to populate a table later. You can create one with no rows and no columns, or specify the columns you expect to use.
empty_df = pd.DataFrame()
print(empty_df)
# Empty table with predefined columns
results = pd.DataFrame(columns=["Name", "Score", "Passed"])
print(results)
An empty DataFrame with predefined columns still has zero rows. You can later assign columns or combine it with other DataFrames. For larger data-building tasks, it is often more efficient to collect records in a list and create the DataFrame once, rather than repeatedly appending one row at a time.
8. Create a DataFrame with a Custom Index
The index argument lets you specify row labels when creating a DataFrame. Use meaningful labels when they help identify records, but remember that an index is separate from ordinary data columns.
data = {
"Name": ["Amina", "Bilal", "Sara"],
"Marks": [86, 73, 92]
}
df = pd.DataFrame(data, index=["S101", "S102", "S103"])
print(df)
Custom index labels can be names, identifiers, dates or other labels appropriate for your analysis. They do not have to be unique, though duplicate labels can make some operations less intuitive. If an identifier should be treated as a normal field, consider keeping it as a column instead.
To convert the index into a regular column later, use reset_index():
df_with_id_column = df.reset_index(names="Student_ID")
print(df_with_id_column)
9. Add a Column After Creating a DataFrame
Sometimes you create a DataFrame first and calculate additional columns afterward. For example, you can calculate revenue from quantity and unit price.
sales = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet"],
"Units": [3, 5, 4],
"Unit_Price": [800, 500, 300]
})
sales["Revenue"] = sales["Units"] * sales["Unit_Price"]
print(sales)
Operations on Series are generally applied element by element, so the matching quantity and price values are multiplied for each row. This is usually clearer than writing a Python loop for a simple column calculation.
For more examples of creating, updating and deleting fields, continue to how to add and drop columns in Pandas.
10. Create a DataFrame by Reading a File
In practical projects, you often do not manually construct every row. Instead, you load a CSV or Excel file, and Pandas returns a DataFrame. The following examples assume the files exist at the specified paths.
df_csv = pd.read_csv("sales.csv")
# For an Excel workbook, install an appropriate Excel engine if needed
df_excel = pd.read_excel("sales.xlsx")
Use read_csv() for CSV files and read_excel() for supported Excel workbooks. Check the resulting columns and data types after loading, because file formats and source values can affect how Pandas interprets the data.
Which Method Should You Use to Create a Pandas DataFrame?
| Input data | Recommended approach | Useful when |
|---|---|---|
| Dictionary of lists | pd.DataFrame(data) | Each column already has its own list of values. |
| List of dictionaries | pd.DataFrame(records) | Each dictionary represents a record or row. |
| List of lists | pd.DataFrame(rows, columns=...) | Data is arranged row by row. |
| NumPy array | pd.DataFrame(array, columns=...) | Values are already stored in a two-dimensional array. |
| Pandas Series | pd.DataFrame({"A": series_a}) | You need to combine labelled Series objects. |
| CSV file | pd.read_csv(...) | You want to import an existing comma-separated file. |
| Excel workbook | pd.read_excel(...) | You want to import a spreadsheet or worksheet. |
The best approach depends on the format of your source data. Choose the representation that makes the relationship between records, fields and labels easiest to understand.
Common Mistakes When Creating a DataFrame
1. Lists have different lengths
When creating a DataFrame from a dictionary of lists, make sure each list has the same number of values. If the source records are incomplete, consider a list of dictionaries instead and inspect the resulting missing values.
2. Column labels do not match the data
When using columns=, check that the number and order of labels match the structure of the input. A mismatch can cause an error or assign confusing names to the values.
3. Confusing a row index with a data column
The index labels displayed on the left are not automatically part of the DataFrame's ordinary columns. If an ID is a business attribute that you need to export or analyse, it may be better stored as a column.
4. Assuming Series are aligned by position
When combining Series into a DataFrame, Pandas aligns values by index labels. If indexes differ, inspect the result for unexpected missing values or use a deliberate index strategy.
5. Forgetting to inspect the result
After creating a DataFrame, run df.head(), df.shape, df.columns and df.dtypes to verify that the data has the expected structure. See the DataFrame inspection guide for details.
Practice Exercises: Create a Pandas DataFrame
- Create a DataFrame with three columns:
Student,AgeandMarks, using a dictionary of lists. - Create the same table using a list of dictionaries.
- Create a DataFrame from a list of lists and assign the column names explicitly.
- Create a DataFrame with student IDs as the index, then use
reset_index()to turn the index into a column. - Create a sales DataFrame with
QuantityandPrice, then calculate aTotalcolumn.
When you finish, inspect each result with head(), shape and dtypes. You can continue practising with the Pandas exercises and solutions page as it becomes available in the tutorial series.
Frequently Asked Questions
How do I create a Pandas DataFrame in Python?
Import Pandas as pd and call pd.DataFrame() with your data. Common inputs include a dictionary of lists, a list of dictionaries, a list of lists, a NumPy array or Pandas Series objects.
What is the easiest way to create a DataFrame?
For small, column-oriented data, a dictionary of lists is often easy to read. If each record is already represented as a dictionary, pass a list of dictionaries to pd.DataFrame().
Can I create a DataFrame without data?
Yes. Use pd.DataFrame() for an empty DataFrame or pass column names with pd.DataFrame(columns=["Name", "Score"]) to define an empty table structure.
How do I name the columns when creating a DataFrame?
For row-oriented data such as a list of lists or a NumPy array, pass the labels using the columns argument. With a dictionary of lists, the dictionary keys become the column names.
How do I set an index when creating a DataFrame?
Pass a list of row labels using the index argument. The number of index labels must correspond to the number of rows. You can later use reset_index() if you need the labels as a regular column.
What is the difference between a Series and a DataFrame?
A Series is one-dimensional and contains one labelled sequence of values. A DataFrame is two-dimensional and organises data into rows and columns. A DataFrame column commonly returns a Series when selected.
Can Pandas create a DataFrame from a CSV file?
Yes. Use pd.read_csv("file.csv"). Pandas reads the file and returns a DataFrame. You should inspect the column names, data types and first rows after importing.
Continue Learning Pandas
Now that you know how to create a DataFrame from common Python data structures, learn how to inspect and work with it:
