Take multiple lists into dataframe

How do I take multiple lists and put them as different columns in a python dataframe? I tried following Read lists into columns of pandas DataFrame but had some trouble.

Attempt 1:

  • Have three lists, and zip them together and use that res = zip(lst1,lst2,lst3)
  • Yields just one column

Attempt 2:

    percentile_list = pd.DataFrame({'lst1Tite' : [lst1],
     'lst2Tite' : [lst2],
      }, columns=['lst1Tite','lst1Tite', 'lst1Tite'])

- yields either one row by 3 columns (the way above) or if I transpose it is 3 rows and 1 column

How do I get a 100 row (length of each independent list) by 3 column (three lists) pandas dataframe?

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

    import pandas as pd
    lst1 = range(100)
    lst2 = range(100)
    lst3 = range(100)
    percentile_list = pd.DataFrame(
        {'lst1Title': lst1,
         'lst2Title': lst2,
         'lst3Title': lst3

        lst1Title  lst2Title  lst3Title
    0          0         0         0
    1          1         1         1
    2          2         2         2
    3          3         3         3
    4          4         4         4
    5          5         5         5
    6          6         6         6

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

    import numpy as np
    percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                                   columns=['lst1Title', 'lst2Title', 'lst3Title'])

From: stackoverflow.com/q/30522724

Back to homepage or read more recommendations: