Creating a Pandas dataframe using list of tuples
We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use.
Code #1: Simply passing tuple to DataFrame constructor.
# import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Name', 'Age', 'Score']) print(df) |
Output:
Code #2: Using from_records()
import pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame.from_records(data, columns =['Team', 'Age', 'Score']) print(df) |
Output:
Code #3: Using from_items()
import pandas as pd # data in the form of list of tuplesdata = [('Age', [18, 15, 17, 18, 17]),('Team', ['A', 'B', 'A', 'C', 'B']),('Score', [7, 6, 8, 7, 5]),] # create DataFrame using datadf = pd.DataFrame.from_items(data) print(df) |
Output:
Code #4: For pivoting it possible.
# import pandas to use pandas DataFrameimport pandas as pd # data in the form of list of tuplesdata = [('Peter', 18, 7), ('Riff', 15, 6), ('John', 17, 8), ('Michel', 18, 7), ('Sheli', 17, 5) ] # create DataFrame using datadf = pd.DataFrame(data, columns =['Team', 'Age', 'Score']) a = df.pivot('Team', 'Score','Age')print(a) |
Output:



