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 DataFrame import pandas as pd # data in the form of list of tuples data = [( 'Peter' , 18 , 7 ), ( 'Riff' , 15 , 6 ), ( 'John' , 17 , 8 ), ( 'Michel' , 18 , 7 ), ( 'Sheli' , 17 , 5 ) ] # create DataFrame using data df = 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 tuples data = [( 'Peter' , 18 , 7 ), ( 'Riff' , 15 , 6 ), ( 'John' , 17 , 8 ), ( 'Michel' , 18 , 7 ), ( 'Sheli' , 17 , 5 ) ] # create DataFrame using data df = 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 tuples data = [ ( 'Age' , [ 18 , 15 , 17 , 18 , 17 ]), ( 'Team' , [ 'A' , 'B' , 'A' , 'C' , 'B' ]), ( 'Score' , [ 7 , 6 , 8 , 7 , 5 ]), ] # create DataFrame using data df = pd.DataFrame.from_items(data) print (df) |
Output:
Code #4: For pivoting it possible.
# import pandas to use pandas DataFrame import pandas as pd # data in the form of list of tuples data = [( 'Peter' , 18 , 7 ), ( 'Riff' , 15 , 6 ), ( 'John' , 17 , 8 ), ( 'Michel' , 18 , 7 ), ( 'Sheli' , 17 , 5 ) ] # create DataFrame using data df = pd.DataFrame(data, columns = [ 'Team' , 'Age' , 'Score' ]) a = df.pivot( 'Team' , 'Score' , 'Age' ) print (a) |
Output:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.