Creating DataFrame based on two or more non equal lists

Question:

I have two lists let’s say

list1 = ["apple","banana"]
list2 = ["M","T","W","TR","F","S"]

I want to create a data frame of two columns fruit and day so that the result will look something like this

fruit day
apple M
apple T
apple W
apple TR
apple F
apple S
banana M

and so on…

currently, my actual data is columnar meaning items in list2 are in columns, but I want them in rows, any help would be appreciated.

Asked By: SayZer

||

Answers:

try this:

from itertools import product
import pandas as pd


list1 = ["apple","banana"]
list2 = ["M","T","W","TR","F","S"]
df = pd.DataFrame(
    product(list1, list2),
    columns=['fruit', 'day']
)
print(df)
>>>
    fruit   day
0   apple   M
1   apple   T
2   apple   W
3   apple   TR
4   apple   F
5   apple   S
6   banana  M
7   banana  T
8   banana  W
9   banana  TR
10  banana  F
11  banana  S
Answered By: ziying35

same result with merge:

df = pd.merge(pd.Series(list1,name='fruit'),
              pd.Series(list2,name='day'),how='cross')

print(df)
'''
     fruit day
0    apple   M
1    apple   T
2    apple   W
3    apple  TR
4    apple   F
5    apple   S
6   banana   M
7   banana   T
8   banana   W
9   banana  TR
10  banana   F
11  banana   S
Answered By: SergFSM
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.