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

Time:11-22

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?

CodePudding user response:

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
  • Related