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:
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 1Each 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
MediumA 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 15Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
7pandas DataFrames
SeriesDataFramesReading CSV FilesInspecting DataSelecting ColumnsRecap: Movie Ratings2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler