Skip to content Skip to sidebar Skip to footer

How Can I Have Separate Columns Of A Dataframe Out Of List Of Tuples And A List

I have the following lists: l1 = [(1,2),(3,4),(5,6)] l2 = [7,8,9] I want the output as df df = c1 c2 c3 0 1 2 7 1 3 4 8 2 5 6 9 So far I can

Solution 1:

2-list form:

pd.DataFrame([*x, y] for x, y in  zip(l1, l2))

   012012713482569

Multi-list form:

from collections importSequence

lists = [l1, l2, ...]
pd.DataFrame([
    [
        k for j in i for k in (j 
        ifisinstance(j, Sequence) else [j]
    )] 
    for i inzip(*lists)
])

   012012713482569

This will work for any case regardless of whether l_i is a list of tuples or list of integers.

Solution 2:

You could also just use pd.concat, and concatenate the dataframes resulting from pd.DataFrame(l1) and pd.Dataframe(l2):

df = pd.concat([pd.DataFrame(l1), pd.DataFrame(l2)], axis=1)

>>> df
   0  1  0
0  1  2  7
1  3  4  8
2  5  6  9

Post a Comment for "How Can I Have Separate Columns Of A Dataframe Out Of List Of Tuples And A List"