Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
pd
dataframe
df
column

How to add a column to pandas dataframe

Educative Answers Team
svg viewer

Python provides a library called pandas that is popular with data scientists and analysts. Pandas enables users to manipulate and analyze data with sophisticated data analysis tools.

Pandas provide two data structures that shape data into a readable form:

  • Series: a one-dimensional data structure that comprises of a key-value pair.
  • Dataframe: a two-dimensional data-structure that can be thought of as a spreadsheet.

Adding a column to dataframe

There are three ways to add a column to dataframe

  1. via list
  2. via df.assign()
  3. via df.insert()
svg viewer

Here is a dataframe that contains Jack’s and John’s fruits.

import pandas as pd

##### INITIALIZATION #####

fruits_jack = ["apples", "oranges", "bananas"]
fruits_john = ["guavas", "kiwis", "strawberries"]
index = ["a", "b", "c"]
all_fruits = {"Jack's": fruits_jack, "John's": fruits_john}

fruits = pd.DataFrame(all_fruits)
print(fruits)

Let’s add another column for James’ fruits: watermelons, grapes, peaches.

import pandas as pd

##### INITIALIZATION #####

fruits_jack = ["apples", "oranges", "bananas"]
fruits_john = ["guavas", "kiwis", "strawberries"]
index = ["a", "b", "c"]
all_fruits = {"Jack's": fruits_jack, "John's": fruits_john}

fruits = pd.DataFrame(all_fruits, index = index)
print(fruits, "\n")

fruits_james = ["watermelons", "grapes", "peaches"]

##### VIA LIST #####

fruits["James'"] = fruits_james
print("Adding James' fruits using list\n")
print(fruits, "\n")

##### Deleting Jack's Column #####
del fruits["James'"]

##### VIA DF.ASSIGN() #####

fruits = fruits.assign(James = fruits_james)
print("Adding James' fruits using df.assign()\n")
print(fruits, "\n")

##### Deleting Jack's Column #####
del fruits["James"]

##### VIA DFINSERT() #####

fruits.insert(2, "James'", fruits_james)
print("Adding James' fruits using df.insert()\n")
print(fruits, "\n")

RELATED TAGS

pandas
pd
dataframe
df
column
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring