cyrus24
cyrus24

Reputation: 363

Adding rows to a column for every element in the list for every unique value in another column in python pandas

I have two lists of unequal length:

Name = ['Tom', 'Jack', 'Nick', 'Juli', 'Harry']
bId= list(range(0,3)) 

I want to build a data frame that would look like below:

'Name' 'bId'
Tom   0
Tom   1
Tom   2
Jack  0
Jack  1
Jack  2
Nick  0
Nick  1
Nick  2
Juli  0
Juli  1
JUli  2
Harry 0
Harry 1
Harry 2

Please suggest.

Upvotes: 0

Views: 287

Answers (1)

jezrael
jezrael

Reputation: 862511

Use itertools.product with DataFrame constructor:

from  itertools import product

df = pd.DataFrame(product(Name, bId), columns=['Name','bId'])
print (df)
     Name  bId
0     Tom    0
1     Tom    1
2     Tom    2
3    Jack    0
4    Jack    1
5    Jack    2
6    Nick    0
7    Nick    1
8    Nick    2
9    Juli    0
10   Juli    1
11   Juli    2
12  Harry    0
13  Harry    1
14  Harry    2

Upvotes: 1

Related Questions