Python - Add columns of different length in pandas

Learn, how can we add columns of different length in Python pandas?
Submitted by Pranit Sharma, on August 15, 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 data.

Problem statement

In pandas, if we try to make columns in a DataFrame with each column having a different length, then it is not possible to create a DataFrame like this.

Add columns of different length in pandas

The only option to add columns of different lengths in pandas DataFrame is to make two different DataFrames having columns of the same length in respective DataFrame but different lengths independently. We will concat these two DataFrames so that columns having different lengths will consider the null values as well.

The df.concat() is a method of combining or joining two DataFrames, it is a method that appends or inserts one (or more) DataFrame below the other.

By using df.concat(), we will pass a parameter called axis=1 as we want to concat the dataframes along the rows.

Let us understand with the help of an example,

Python program to add columns of different length in pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dictionaries
d1 = {
    'Name':['Ram','Shyam','Seeta','Geeta'],
    'Grades':['A','C','A','B']
}

d2 = {
    'Name':['Jhon','Wilson','Mike'],
    'Grades':['D','C','A']
}

# Creating DataFrame
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# Display Original DataFrames
print("Created DataFrame 1:\n",df1,"\n")

print("Created DataFrame 2:\n",df2,"\n")

# Concatenating two DataFrames
result = pd.concat([df1,df2],axis=1)

# Display result
print("Result:\n",result)

Output

Example: Add columns of different lengths

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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