Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Creating a Pandas dataframe using list of tuples

  • Last Updated : 06 Jan, 2019

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.

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




# 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!