To convert a tuple to DataFrame in Python, you can use the “pd.DataFrame()” constructor that accepts a tuple as an argument and returns a DataFrame.
Example
import pandas as pd
data = [('Facebook', 750, True),
('Alphabet', 1100, True),
('Amazon', 1700, True),
('Apple', 2100, False),
('Microsoft', 1750, False)]
df = pd.DataFrame(data, columns=['Name', 'M-cap', 'Internet Companies'])
print(df)
Output
Name M-cap Internet Companies
0 Facebook 750 True
1 Alphabet 1100 True
2 Amazon 1700 True
3 Apple 2100 False
4 Microsoft 1750 False
First, we imported the Pandas module and then defined a list of tuples, and then passed that list of tuples to the DataFrame constructor in addition to columns, and it returned the DataFrame.
Using the from_records() method to create a DataFrame
Pandas from_records() is a library method that creates a DataFrame object from a structured ndarray, tuples, dictionaries, or DataFrame.
import pandas as pd
data = [('Facebook', 750, True),
('Alphabet', 1100, True),
('Amazon', 1700, True),
('Apple', 2100, False),
('Microsoft', 1750, False)]
df = pd.DataFrame.from_records(
data, columns=['Name', 'M-cap', 'Internet Companies'])
print(df)
Output
Name M-cap Internet Companies
0 Facebook 750 True
1 Alphabet 1100 True
2 Amazon 1700 True
3 Apple 2100 False
4 Microsoft 1750 False
In this example, we use the from_records() pandas method and pass the data and columns, and it returns the DataFrame.
Converting tuple of tuples to DataFrame
To convert a tuple of tuples into DataFrame in Python, convert a tuple of tuples into a list of tuples and use the DataFrame constructor to convert a list of tuples into DataFrame.
import pandas as pd
data = (('Facebook', 750, True),
('Alphabet', 1100, True),
('Amazon', 1700, True),
('Apple', 2100, False),
('Microsoft', 1750, False))
dataList = list(data)
df = pd.DataFrame(
dataList, columns=['Name', 'M-cap', 'Internet Companies'])
print(df)
Output
Name M-cap Internet Companies
0 Facebook 750 True
1 Alphabet 1100 True
2 Amazon 1700 True
3 Apple 2100 False
4 Microsoft 1750 False
And we get the exact DataFrame. Converting a List to DataFrame is a straightforward task, so if we somehow convert any data type to a list, it will be clear to create a DataFrame from the list.