Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to join two objects in python in such a way that all values in one of the objects are duplicated for each value in the other object

I am working with two python objects. One is a list of names, called "People", the other is a list of dates, called "Dates". They are structured as below:

Image with the structure I am looking for

I have tried a few ways to get this to work using joins with the following coming the closest:

Names_Dates = pd.concat([Names, Dates], axis=1, join='inner')

However, this does not achieve the goal of replicating the Dates for each value in Names. Any thoughts on a solution?

like image 980
Colson Perkins Avatar asked Dec 04 '25 16:12

Colson Perkins


1 Answers

You want itertools.product:

import itertools
names = ['John', 'Mary', 'Alex']
dates = ['1/13/2019', '1/14/2019', '1/15/2019']

print(list(itertools.product(names, dates)))

Output:

[('John', '1/13/2019'), ('John', '1/14/2019'), ('John', '1/15/2019'), ('Mary', '1/13/2019'), ('Mary', '1/14/2019'), ('Mary', '1/15/2019'), ('Alex', '1/13/2019'), ('Alex', '1/14/2019'), ('Alex', '1/15/2019')]

If you want to iterate over the name, date tuples, you can do something like this:

import itertools
names = ['John', 'Mary', 'Alex']
dates = ['1/13/2019', '1/14/2019', '1/15/2019']

for name, date in itertools.product(names, dates):
    print(name, date)

Output:

John 1/13/2019
John 1/14/2019
John 1/15/2019
Mary 1/13/2019
Mary 1/14/2019
Mary 1/15/2019
Alex 1/13/2019
Alex 1/14/2019
Alex 1/15/2019
like image 141
Sumner Evans Avatar answered Dec 07 '25 05:12

Sumner Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!