CodeBlanks Logo Icon CodeBlanks

Creating a DataFrame

A DataFrame is created with pd.DataFrame() from a dictionary or list.

DataFrame from a dict

The easiest way is a dict whose keys are column names and whose values are lists:

df = pd.DataFrame({
    "ad": ["Ali", "Ece", "Can"],
    "yas": [34, 28, 45],
})
print(df.shape)   # (3, 2)

All lists must have the same length; otherwise a ValueError occurs.

From a list of rows and from NumPy

If the data comes row by row, a list of lists and columns are used:

satirlar = [["Ali", 34], ["Ece", 28]]
df = pd.DataFrame(satirlar, columns=["ad", "yas"])

import numpy as np
df2 = pd.DataFrame(np.zeros((2, 3)), columns=["a", "b", "c"])

The other direction is easy too: df.to_numpy() turns a numeric table into a NumPy array.

Practice Build a table

Create a DataFrame with urun and fiyat columns (with a dict). Print its shape and its column names with columns.tolist().

Starter code

model.py
import pandas as pd

# buraya yaz

Sample solution

model.py
import pandas as pd

df = pd.DataFrame({"urun": ["kalem", "defter", "silgi"], "fiyat": [10, 25, 5]})
print(df.shape)
print(df.columns.tolist())

Expected output

(3, 2)
['urun', 'fiyat']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the shape of a DataFrame built from a dict with three keys and 5-element lists?

  • (5, 3) Correct answer
  • (3, 5)
  • (15,)
  • (5,)

Explanation: Each key is a column and each list element is a row.

2 Specify the column names.

Question
df = pd.DataFrame(satirlar, ____=["ad", "yas"])
Answer
df = pd.DataFrame(satirlar, columns=["ad", "yas"])

Explanation: The columns parameter gives the column names in order.

3 Match the conversions.

Term Meaning
pd.DataFrame(dict) Table from a dict
columns= Column names
df.to_numpy() To a NumPy array
df.shape Row and column count

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation