Creating a DataFrame
A DataFrame can be built from almost any shape of data — lists, dictionaries, Series, even NumPy arrays. The one thing to keep track of is what ends up as the columns and what ends up as the row index.
Flip through the builder to preview each source, then run the real code in the panels below.
A DataFrame can be born from many shapes of data. Pick a source and see the code and the table it produces.
import pandas as pd df = pd.DataFrame({ 'Name': ['Rinku', 'Ritu', 'Pankaj'], 'English': [65, 77, 72], 'IP': [89, 83, 95], }) print(df)
Name | English | IP | |
|---|---|---|---|
0 | Rinku | 65 | 89 |
1 | Ritu | 77 | 83 |
2 | Pankaj | 72 | 95 |
💡 Dict of lists: The dictionary's keys become the COLUMN names; each list is a column.
1From a list (and a list of lists)
A single list becomes one column (auto-named 0). A list of lists makes each inner list a row — pass columns=[…] to name the columns.
2From a dictionary of lists
This is the most common way. Each key becomes a column name and its list becomes that column's values.
index=[...] to label the rows yourself instead of the default 0, 1, 2… — but the index list must be the same length as the data.3From a dictionary of Series
Each Series becomes a column, and the Series' index becomes the shared row index — a neat way to line up data by label.
4From a dictionary of dictionaries
Here the outer keys become columns and the inner keys become rows. If an inner dictionary is missing a key that another has, that cell becomes NaN — just like aligning Series.
5From a NumPy array & another DataFrame
A 2-D NumPy array maps straight onto a grid — name the columns (and rows) if you like. And you can always copy an existing DataFrame by passing it to pd.DataFrame().
pd.DataFrame(data, ...). Watch what the keys/columns= become (column names) and what the index= or Series/dict keys become (row labels).You build pd.DataFrame({'A': [1,2], 'B': [3,4]}). What are 'A' and 'B'?
A dictionary of dictionaries has an inner key missing in one column. That cell becomes…