Creating a Pandas dataframe using list of tuples
A Pandas DataFrame is an important data structure used for organizing and analyzing data in Python. Converting a list of tuples into a DataFrame makes it easier to work with data. In this article we'll see ways to create a DataFrame from a list of tuples.
1. Using pd.DataFrame()
The simplest method to create a DataFrame is by using the pd.DataFrame() function. We pass list of tuples along with column names. We will be using the Pandas library for its implementation.
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])
print(df)
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame(data, columns =['Name', 'Age', 'Score'])
print(df)
Output:

2. Using from_records()
Another method to create a DataFrame is using the df.from_records() method. This method is useful when dealing with structured data.
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score'])
print(df)
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score'])
print(df)
Output:

3. Using pivot()
In some cases we may want to reorganize our DataFrame into a pivot table. We can do this by using the pivot() function. This will help us to change the layout of the DataFrame.
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame(data, columns =['Team', 'Age', 'Score'])
a = df.pivot(index='Team', columns='Score', values='Age')
print(a)
import pandas as pd
data = [('ANSH', 22, 9),
('SAHIL', 22, 6),
('JAYAN', 23, 8),
('AYUSHI', 21, 7),
('SPARSH', 20, 8) ]
df = pd.DataFrame(data, columns =['Team', 'Age', 'Score'])
a = df.pivot(index='Team', columns='Score', values='Age')
print(a)
Output:

As we continue working with Pandas these methods will help in the strong foundation for efficiently handling and analyzing data in future projects.