Pandas: Create dataframe from list of namedtuple

Given a list of namedtuple, we have to create dataframe from it. By Pranit Sharma Last updated : October 03, 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.

Tuples is also another built-in data type of python used to store heterogeneous elements, elements inside tuples are encapsulated in normal parenthesis. Tuples are considered as a series or collection and we can perform operations like insert, update, and delete with its elements.

We know that Pandas DataFrames can be created with the help of dictionaries or arrays but in real-world analysis, first, a CSV file or an xlsx file is imported and then the content of CSV or excel file is converted into a DataFrame. But here, we are supposed to create a pandas DataFrame with the help of a tuple.

Creating pandas dataframe from list of namedtuple

Here, we will use the namedtuple() method which is a method used for naming a tuple, inside this method, we can pass the name of tuple and some random variables in a list. Later we can fill in these variables.

Let us understand with the help of an example,

Python program to create dataframe from list of namedtuple

# Importing pandas package
import pandas as pd

# Import collections
import collections

# Importing namedtuple from collections
from collections import namedtuple

# Creating a namedtuple
Point = namedtuple('Point', ['x', 'y'])

# Assiging tuples some values
points = [Point(1, 2), Point(3, 4)]

# Creating DataFrame
df = pd.DataFrame(points)

# Display original DataFrame
print('Original DataFrame:\n',df,'\n')

Output

The output of the above program is:

Example: Pandas: Create dataframe from list of namedtuple

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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