Inserting and deleting columns to a DataFrame
In this section, we will see how to insert and delete columns to a data frame.
Getting ready
Run the following code to load NumPy, and pandas, and to initialize a DataFrame
object:
import numpy as np import pandas as pd df1 = pd.DataFrame([['Pen', 24, 2.39], ['Eraser', 32, 1.29], ['Sharpener', 12, 10.39], ['Pencil', 42, 0.59 ]], index=[100024, 201024, 202034, 101122], columns = ['item', 'inventory', 'unit_price'])
How to do it...
To insert a column, run the following cell:
df['discount'] = [0.75, 0.50, 0.75, 0.75]
To delete a column, use the following code:
del df['discount']
How it works...
We can think of a DataFrame
as a dictionary, where the dictionary keys are the column names. So, to insert a column, we can use the following code:
df['column_name'] = <iterable>
The <iterable>
can be for example, a list, a NumPy array, or a pandas Series
object...