Reputation: 149
I want to create a df with data range values. I can create the df like this:
def create_df(start='2021-01-01', end='2022-12-31'):
df = pd.DataFrame({"Date": pd.date_range(start,end)})
return df
df = create_df()
Gives the following df
Date
0 2021-01-01
1 2021-01-02
2 2021-01-03
3 2021-01-04
4 2021-01-05
Now I want to create a second column A with elements from a list. There should be one df with repeated date values for each element of the list. This is what I want
Date A
0 2021-01-01 1
1 2021-01-02 1
2 2021-01-03 1
.............
729 2022-12-31 1
730 2021-01-01 2
How can I create one df with the repeated data range for all element in the list?
Upvotes: 1
Views: 76
Reputation: 863256
Use product
for repeat values of lists with date ranges:
from itertools import product
def create_df(start='2021-01-01', end='2022-12-31', L=[1,2,3]):
df = pd.DataFrame(product(L, pd.date_range(start,end)), columns=['A','Date'])
return df[['Date','A']]
df = create_df()
print (df)
Date A
0 2021-01-01 1
1 2021-01-02 1
2 2021-01-03 1
3 2021-01-04 1
4 2021-01-05 1
... ..
2185 2022-12-27 3
2186 2022-12-28 3
2187 2022-12-29 3
2188 2022-12-30 3
2189 2022-12-31 3
[2190 rows x 2 columns]
Upvotes: 2