
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Adding new column to existing DataFrame in Pandas
Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list and series etc. In this article we will see how to add a new column to an existing data frame. So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no.
Example
import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) print (df)
Output
Running the above code gives us the following result:
Month_No 0 6 1 8 2 3 3 1 4 12
using insert() function
We can use the insert() function of pandas which will insert the column at the position specified by its index. Below we add No of Days in a month as a column to the existing pandas DataFrame at index position 1.
Example
import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) # Insert the new column at position 1. df.insert(1,"No_of_days",[30,31,31,31,31],True) print (df)
Output
Running the above code gives us the following result −
Month_No No_of_days 0 6 30 1 8 31 2 3 31 3 1 31 4 12 31
Using assign() function
The assign() function
Example
import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) # Insert a column at the end df = df.assign(No_of_days = [30,31,31,31,31]) print (df)
Output
Running the above code gives us the following result −
Month_No No_of_days 0 6 30 1 8 31 2 3 31 3 1 31 4 12 31
- Related Articles
- Adding a new column to existing DataFrame in Pandas in Python
- Adding a new column to an existing DataFrame in Python Pandas
- Adding new enum column to an existing MySQL table?
- Adding a new NOT NULL column to an existing table with records
- Python – Create a new column in a Pandas dataframe
- How can a new column be added to an existing dataframe in Python?
- Python - Add a new column with constant value to Pandas DataFrame
- Append list of dictionaries to an existing Pandas DataFrame in Python
- Apply uppercase to a column in Pandas dataframe
- Adding characters in values for an existing int column in MySQL?
- How to rename column names in a Pandas DataFrame?
- How to add column from another DataFrame in Pandas?
- How to shift a column in a Pandas DataFrame?
- Pandas series Vs. single-column DataFrame
- How to delete a column from Pandas DataFrame
