

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- How can a new column be added to an existing dataframe in Python?
- Python – Create a new column in a Pandas dataframe
- 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 delete a column from Pandas DataFrame
- Python - Add a zero column to Pandas DataFrame
- 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?