Skip to content Skip to sidebar Skip to footer

Pandas: Inserting New Row Based On Date Condition For Each Group

I have a dataframe like below: Date Group Value Duration 2018-01-01 A 20 30 2018-02-01 A 10 60 2018-01-01 B 15 180 2018-

Solution 1:

Use pd.MultiIndex to reindex your df:

df["Date"] = pd.to_datetime(df["Date"])

s = pd.MultiIndex.from_product([df["Date"].unique(),df["Group"].unique()],names=["Date","Group"])

print (df.set_index(["Date","Group"]).reindex(s)
       .reset_index()
       .sort_values(["Group","Date"])
       .ffill())

        Date Group  Value  Duration
0 2018-01-01     A   20.0      30.0
3 2018-02-01     A   10.0      60.0
6 2018-03-01     A   10.0      60.0
1 2018-01-01     B   15.0     180.0
4 2018-02-01     B   30.0     210.0
7 2018-03-01     B   25.0     238.0
2 2018-01-01     C   10.0     235.0
5 2018-02-01     C   10.0     235.0
8 2018-03-01     C   10.0     235.0

Post a Comment for "Pandas: Inserting New Row Based On Date Condition For Each Group"