How to create a dataframe while preserving order of the columns?

Learn, how can we create a dataframe while preserving order of the columns? By Pranit Sharma Last updated : September 30, 2023

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

We are supposed to create a DataFrame with multiple NumPy arrays or pandas Series while preserving the order of each item, we will pass the key-value tuple pair for order preservation.

Creating a dataframe while preserving order of the columns

We will use the OrderedDict() method which is a method of collections library. We will pass the key-value pair inside OrderedDict(). Since while constructing a dictionary, the order is randomized, OrderedDict() will work accordingly if we pass a key-value tuple pair.

Let us understand with the help of an example,

Python program to create a dataframe while preserving order of the columns

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Importing orderdict method 
# from collections
from collections import OrderedDict

# Creating numpy arrays
arr1 = np.array([23,34,45,56])
arr2 = np.array([67,78,89,90])

# Creating DataFrame
df = pd.DataFrame(OrderedDict({'col1':pd.Series(arr1),'col2':pd.Series(arr2)}))

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

Output

The output of the above program is:

Create a dataframe while preserving order of the columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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