This video shows 3 ways to add remove columns from Data Frames in the Pandas library for Python.

Code used in this Python Code Clip:

import pandas as pd

import statsmodels.api as sm #(To access mtcars dataset)
mtcars = sm.datasets.get_rdataset(“mtcars”, “datasets”, cache=True).data

mtcars.head()

Add row to end of data frame with df.append()

row = mtcars.loc[“Volvo 142E”,]

mtcars = mtcars.append(row)

mtcars.tail()

Add a new row by assignment with index name

mtcars.loc[“NEW_CAR”] = [0,1,2,3,4,5,6,7,8,9,10]

mtcars.tail()

Insert row at given position

Construct a row to insert as a data frame

row_values = [12,35,46,27,28,24,23,13,64,34,64]
insert_row = pd.DataFrame({v: row_values[k] for k, v in enumerate(mtcars.columns)},
index = [“Insert_Car”])

Choose an insertion index

insert_index = len(mtcars.index)-2

Use indexing to append rows

mtcars = mtcars.iloc[:insert_index,].append([insert_row, mtcars.iloc[insert_index:,]])

mtcars.tail()

► Subscribe: https://www.youtube.com/c/DataDaft/featured

#python

How to Add a Row To a Data Frames in the Pandas library for Python
1.95 GEEK