How to create a data frame using two lists in Python?

Question:

L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']

Desired Output 1: D1 = {'a':['Cat','Dog'],
                    'b':['Fish','Frog'],
                    'c':['Crow','Eagle']}

Desired Output 2: DF1 =   A        B        C   
                     Cat      Fish      Crow
                     Dog      Frog      Eagle

I only used from a to c for reference, I’ve more than 100 columns in DataFrame.

Could someone please help me with this?

Asked By: Srikanth

||

Answers:

Try:

L1 = ["a", "b", "c", "a", "b", "c"]
L2 = ["Cat", "Fish", "Crow", "Dog", "Frog", "Eagle"]

out = {}
for a, b in zip(L1, L2):
    out.setdefault(a, []).append(b)

print(out)

Prints:

{"a": ["Cat", "Dog"], "b": ["Fish", "Frog"], "c": ["Crow", "Eagle"]}

Then you can do:

out_df = pd.DataFrame(out)
out_df.columns = out_df.columns.str.upper()

print(out_df)

Prints:

     A     B      C
0  Cat  Fish   Crow
1  Dog  Frog  Eagle
Answered By: Andrej Kesely

Here is a way by creating a blank dictionary and then appending each item to it.

l = list(set(l1))
d = {key:[] for key in l}
for i,j in zip(l1,l2):
    d.get(i).append(j)
Answered By: rhug123
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.