CodeBlanks Logo Icon CodeBlanks

Column operations

DataFrame columns are accessed with brackets and statistics are computed on them.

Selecting and adding columns

A single column is selected with df["ad"], several with df[["ad", "yas"]]. A new column is added by computing it from existing ones:

df["yillik"] = df["maas"] * 12
df["genc"] = df["yas"] < 30

The operation is applied to the whole column at once; it is the same as vectorisation in NumPy.

Dropping and renaming

Column operations return a new DataFrame; the original table doesn't change:

df2 = df.drop(columns=["genc"])
df3 = df.rename(columns={"maas": "ucret"})
print(df["maas"].sum())   # column total

To use the result, assign it to a new variable or write df = df.drop(...).

Practice Computed column

Add a yillik column to df equal to 12 times maas. Print the total of this column.

Starter code

model.py
import pandas as pd

df = pd.DataFrame({
    "ad": ["Ali", "Ece", "Can", "Su"],
    "yas": [34, 28, 45, 22],
    "maas": [5000, 4200, 7100, 3000],
})

# buraya yaz

Sample solution

model.py
import pandas as pd

df = pd.DataFrame({
    "ad": ["Ali", "Ece", "Can", "Su"],
    "yas": [34, 28, 45, 22],
    "maas": [5000, 4200, 7100, 3000],
})

df["yillik"] = df["maas"] * 12
print(df["yillik"].sum())

Expected output

231600

Questions and answers

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

1 What is the difference between <code>df[["ad"]]</code> and <code>df["ad"]</code>?

  • There is no difference
  • The first errors
  • The second returns a list
  • The first returns a one-column DataFrame, the second a Series Correct answer

Explanation: Giving names inside a list always returns a DataFrame.

2 Remove the maas column from the table.

Question
df2 = df.____(columns=["maas"])
Answer
df2 = df.drop(columns=["maas"])

Explanation: drop(columns=[...]) returns a new table without the given columns.

3 Match the expressions.

Term Meaning
df["yas"] Series
df[["yas", "ad"]] Two-column table
df.rename Renaming
df["y"] = ... New column

All lessons in Beginner

13 Project: Classification

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