columns with year between two dates

Viewed 33

I would like to create a dataframe with the years between to dates.

START END

the final data frame would be like that.

final data Frame

Many thanks

1 Answers

Example data:

df = pd.DataFrame({
    "Start date": [2022, 2021, 2021, 2022],
    "Maturity": [2023, 2022, 2025, 2028],
})

Solution:

start = df["star"].min()
end = df["end"].max()

for year in range(start, end+1):
    df[year] = np.where((df["start"] <= year) & (df["end"] >= year), year, np.nan)

Output:enter image description here

Related