Search⌘ K
AI Features

Insert Columns into a Pandas DataFrame

Explore methods to insert columns into pandas DataFrames correctly. Understand why using square bracket notation is preferred over attribute access to avoid confusion and errors. Learn how to manage DataFrame metadata efficiently while practicing safe column addition techniques.

We'll cover the following...

Try it yourself

Try executing the code below to see the result.

Python 3.8
import pandas as pd
df = pd.DataFrame([
['Sterling', 83.4],
['Cheryl', 97.2],
['Lana', 13.2],
], columns=['name', 'sum'])
df.late_fee = 3.5
print(df)

Explanation

Where did the late_fee column go? Python’s objects are very dynamic. We can add attributes to most of them as we please.

In [1]: class Point:
...: def __init__(self, x, y):
...: self.x, self.y = x, y
In [2]: p = Point(1, 2)
In [3]: p.x, p.y
Out[3]: (1, 2)
In [4]: p.z = 3
In [5]: p.z
Out[5]:
...