Here are two ways to convert a tuple to DataFrame in Python:
- Using pd.DataFrame()
- Using from_records()
Method 1: Using pd.DataFrame()
This DataFrame constructor approach is straightforward and works well for simple tuples. If the tuple contains nested tuples or lists, each nested tuple/list becomes a row in the DataFrame.
import pandas as pd
list_of_tuples = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
print("Before converting to data frame")
print(data)
df = pd.DataFrame(list_of_tuples, columns=['col1', 'col2', 'col3'])
print("After converting to data frame")
print(df)
Output
To convert a tuple of tuples into DataFrame, 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
tuple_of_tuples = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9))
print("Before converting to data frame")
print(data)
dataList = list(data)
df = pd.DataFrame(tuple_of_tuples, columns=['col1', 'col2', 'col3'])
print("After converting to data frame")
print(df)
Output
Method 2: Using from_records()
The from_records() method of Pandas is particularly helpful for converting a list of tuples (or other sequences) to a DataFrame. Each tuple in the list becomes a row in the DataFrame.
import pandas as pd
list_of_tuples = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
print("Before converting to data frame")
print(data)
df = pd.DataFrame.from_records(list_of_tuples,
columns=['col1', 'col2', 'col3'])
print("After converting to data frame")
print(df)
Output
That’s it!