Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to turn three individual tuples into a pandas dataframe?

I have the following tuples with data:

      import pandas as pd

      tuple_1 = [1,2,3,4,5]
      tuple_2 = ['a', 'b', 'c', 'd', 'e']
      tuple_3 = [10,20,30,40,50]

I would like to build a dataframe containing these three tuples as columns of the dataframe.

When I do, with just a tuple is working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      df = pd.DataFrame(data=tuple_1, columns=['Tuple 1'])
      print(df)


      Tuple 1
         1
         2
         3
         4
         5

However, when I tried to do for the three tuples occurs the error:

       df = pd.DataFrame(data=[tuple_1, tuple_2, tuple_3], columns=['Tuple 1', 'Tuple 2', 'Tuple 3'])

ValueError: 3 columns passed, passed data had 5 columns

The desired output is:

       Tuple 1    Tuple 2   Tuple 3
         1          a         10
         2          b         20
         3          c         30
         4          d         40
         5          e         50

>Solution :

Use a dictionary:

df = pd.DataFrame({'Tuple 1': tuple_1, 'Tuple 2': tuple_2, 'Tuple 3': tuple_3})

NB. Your "tuples" are actually lists

You could also fix your approach using zip to transpose the data:

df = pd.DataFrame(data=zip(*[tuple_1, tuple_2, tuple_3]), columns=['Tuple 1', 'Tuple 2', 'Tuple 3'])

Output:

   Tuple 1 Tuple 2  Tuple 3
0        1       a       10
1        2       b       20
2        3       c       30
3        4       d       40
4        5       e       50
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading