Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you give a date range then have that daterange be appended to the dataframe?

I know how to generate a daterange using this code:

pd.date_range(start='2022-10-16', end='2022-10-19')

How do I get the daterange result above and loop through every locations in the below dataframe?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+----------+
| Location |
+----------+
| A        |
| B        |
| C        |
+----------+

This is the result I want.

+----------+------------+
| Location |    Date    |
+----------+------------+
| A        | 2022/10/16 |
| A        | 2022/10/17 |
| A        | 2022/10/18 |
| A        | 2022/10/19 |
| B        | 2022/10/16 |
| B        | 2022/10/17 |
| B        | 2022/10/18 |
| B        | 2022/10/19 |
| C        | 2022/10/16 |
| C        | 2022/10/17 |
| C        | 2022/10/18 |
| C        | 2022/10/19 |
+----------+------------+

I have spent the whole day figuring this out. Any help would be appreciated!

>Solution :

You seem to be looking for a cartesian product of two iterables, which is something itertools.product can do. Take a look at this article.

In your case, you can try:

import pandas as pd
from itertools import product

# Test data:
df = pd.DataFrame(['A', 'B', 'C'], columns=['Location'])
dr = pd.date_range(start='2022-10-16', end='2022-10-19')

# Create the cartesian product:
res_df = pd.DataFrame(product(df['Location'], dr), columns=['Location', 'Date'])
print(res_df)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading