LambdaLab
Informatics Practices · Class 12 · Python Pandas · DataFrame
PandasDataFrame⏱️ 10 min read

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.

DataFrame builder

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
Rinku6589
1
Ritu7783
2
Pankaj7295

💡 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.

from_lists.py

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.

dict_of_lists.py
Tip
Add 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.

dict_of_series.py

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.

dict_of_dicts.py

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().

from_ndarray.py
Key Takeaway
The pattern is always pd.DataFrame(data, ...). Watch what the keys/columns= become (column names) and what the index= or Series/dict keys become (row labels).
Quick Check

You build pd.DataFrame({'A': [1,2], 'B': [3,4]}). What are 'A' and 'B'?

Quick Check

A dictionary of dictionaries has an inner key missing in one column. That cell becomes…