Add column in DataFrame from list

Given a Pandas DataFrame, we have to add column from the list. Submitted by Pranit Sharma, on June 24, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values.

Problem statement

Given a Pandas DataFrame, we have to add column from the list.

Adding column in DataFrame from list

To add a column in DataFrame from a list, for this purpose will create a list of elements and then assign this list to a new column of DataFrame.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to add column in DataFrame from list

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {'A':[1,2,3,4,5,6,7,8,9]}

# Creating dataframe
df = pd.DataFrame(d)

# Display DataFrame
print("Created DataFrame:\n",df,"\n")

# list making
list = [10,20,30,40,50,60,70,80,90]

# Inserting a new column
df['D'] = list

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Created DataFrame:
    A
0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9 

Modified DataFrame:
    A   D
0  1  10
1  2  20
2  3  30
3  4  40
4  5  50
5  6  60
6  7  70
7  8  80
8  9  90

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.