pandas DataFrame: Create and Inspect a Table
Build a table from a dictionary, then look at its rows, columns and types in a few commands.
- Creating a DataFrame from a dict
- head(), shape, columns and dtypes
- Selecting a column
- 0
- 1
- 2
- Ada
- Lin
- Sam
- 95
- 88
- 91
A labeled table
The problem
Real data comes as tables: students with names and scores, sales with dates and amounts. Lists of lists lose the column names, and NumPy arrays want one type per array. pandas gives you a table with labeled columns of different types.
Think of it like this
A DataFrame is like a spreadsheet inside Python. Each column has a name and holds one kind of value, each row is one record, and the row numbers on the left let you point at any row.
pd.DataFrame({...})📊 Create a sheet"name": [...]🏷️ A column called name0, 1, 2🔢 The row labels on the left (the index)students["score"]📈 Pick one whole columnA pandas DataFrame is a two-dimensional table with labeled columns, which can hold different data types, and labeled rows called the index.
Key points
pd.DataFrame({...})turns a dictionary into a table: each key becomes a column.- Each list holds the values of one column; all lists must have the same length.
- The row labels 0, 1 and 2 form the index, created automatically.
nameholds text andscoreholds numbers in the same table.
When should you use it?
- Working with any table: CSV and Excel files, database results, survey data.
- Cleaning, filtering, grouping and summarizing data.
- Preparing data for charts and machine learning.
When not to use it
- A handful of values: a list or a dictionary is simpler.
- Pure numeric grids for heavy maths: NumPy arrays are lighter and faster.
Example code
import pandas as pd
students = pd.DataFrame({
"name": ["Ada", "Lin", "Sam"],
"score": [95, 88, 91],
})
print(students)
Result of running the code
name score
0 Ada 95
1 Lin 88
2 Sam 91
Code explanation
A dictionary of equally sized lists becomes a DataFrame. Each dictionary key supplies a column label.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.
Common mistakes
Columns of different lengths
Every column must have one value per row.
pd.DataFrame({"name": ["Ada", "Lin"], "score": [95]}) # ValueError
pd.DataFrame({"name": ["Ada", "Lin"], "score": [95, 88]})
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Min-Max Normalization Rescale a feature so its smallest value becomes 0 and its largest becomes 1. Easy