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:
There are three ways to add a column to dataframe
df.assign()
df.insert()
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_jamesprint("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")
Free Resources