Understand the idea
A DataFrame is a table. A dictionary supplies the column names and lists of values; items at the same position become one row.
A small example
Names ["Ada", "Ben"] and ages [4, 7] become two rows: Ada · 4, then Ben · 7.
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
import pandas as pd
data = {
"candy": ["Gummy Bear", "Choco Pop", "Mint Bite", "Berry Loop"],
"price": [1.2, 2.1, 1.5, 2.8],
}
df = pd.DataFrame(data)
dfWhat each part does
import pandas as pd- load pandas and give it the short name pd
data =- save our dictionary under the name data
{ }- a dictionary pairs column names with their values
[ ]- a list holds the values of one column in row order
"price"- quotes make text; numbers such as 1.2 need no quotes
pd.DataFrame(data)- turn that dictionary into a table
df =- store the table under the name df
Your inputs
Build the table from the values below. No table is created for you.
| candy | price |
|---|---|
| Gummy Bear | 1.2 |
| Choco Pop | 2.1 |
| Mint Bite | 1.5 |
| Berry Loop | 2.8 |
Your task · Follow
- Write a dictionary named data using the two columns and four rows in the given table.
- Import pandas as pd, create df from data, and display df.
- Use: DataFrame().
Hint
A dictionary pairs each quoted column name with a list; both lists need the same number of rows.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
import pandas as pd
data = {
"candy": ["Gummy Bear", "Choco Pop", "Mint Bite", "Berry Loop"],
"price": [1.2, 2.1, 1.5, 2.8],
}
df = pd.DataFrame(data)
dfOptional stretch
Try adding one extra value to just one column list. Why can pandas no longer pair values into complete rows?