Menu
CoddyTech

DataFrames

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 32 of 60.

A dataset has many columns side by side, one per feature. pandas keeps them together in a DataFrame, a table:

The pets DataFrame drawn as a grid: the column names name, animal and age on top, the row labels 0, 1 and 2 at the side, and row 0, Rex the dog of 4, highlighted as one sample

Build one from a dictionary: curly braces that map each column name to its list of values.

pets = pd.DataFrame({
    "name": ["Rex", "Tom", "Bubbles"],
    "animal": ["dog", "cat", "fish"],
    "age": [4, 2, 1],
})
print(pets)

This prints:

      name animal  age
0      Rex    dog    4
1      Tom    cat    2
2  Bubbles   fish    1

Each list became a column, in your order, and the rows are numbered from 0. The lists need equal lengths: every row needs a value in every column.

challenge icon

Challenge

Medium

A plant shop sells a fern, a cactus and a palm. plants and prices hold their names and prices, and the program reads today's sales into sold.

Build a DataFrame shop with the columns plant, price and sold, in that order, and print it. For the input 8, 2, 15:

    plant  price  sold
0    fern    4.5     8
1  cactus    2.0     2
2    palm   12.0    15

Try it yourself

import pandas as pd

plants = ["fern", "cactus", "palm"]
prices = [4.5, 2.0, 12.0]
sold = [int(input()), int(input()), int(input())]

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler