Creating DataFrames

Most DataFrames in real projects come from loading a file, but building one directly from Python data is what makes it possible to follow along with examples like the ones in this course.

From a dictionary of columns

The most common way, and the one you saw in the last lesson — each key becomes a column, each list becomes that column's values, and every list must be the same length:

>>> column-oriented
import pandas as pd

df = pd.DataFrame({
    "city": ["Delhi", "Mumbai", "Pune"],
    "population_millions": [32.9, 20.7, 7.4]
})
print(df)
Output
     city  population_millions
0   Delhi                 32.9
1  Mumbai                 20.7
2    Pune                  7.4

From a list of rows

The other direction — a list of dictionaries, one per row — reads more naturally when your data already arrives record-by-record, like from an API response:

>>> row-oriented
rows = [
    {"city": "Delhi", "population_millions": 32.9},
    {"city": "Mumbai", "population_millions": 20.7},
    {"city": "Pune", "population_millions": 7.4}
]
df = pd.DataFrame(rows)
print(df)
Output
     city  population_millions
0   Delhi                 32.9
1  Mumbai                 20.7
2    Pune                  7.4

Same table, either way — pick whichever shape your source data is already in.

Inspecting a DataFrame

Before doing anything else with a DataFrame, these four are worth checking on reflex:

>>> quick inspection
print(df.shape)
print(df.columns)
print(df.dtypes)
print(df.head(2))
Output
(3, 2)
Index(['city', 'population_millions'], dtype='object')
city                    object
population_millions    float64
dtype: object
     city  population_millions
0   Delhi                 32.9
1  Mumbai                 20.7

.shape gives (rows, columns), .columns lists the column names, .dtypes shows the data type pandas inferred for each column, and .head(n) shows just the first n rows — the default is 5 if you leave the number out.

Note: pandas often infers a column's dtype as object even for a column of plain strings — that's not an error, it's just how pandas represents text internally (a NumPy-inherited quirk). Numeric columns get proper int64/float64 types.