dynamically remap or ffill values across columns in python

Solution for dynamically remap or ffill values across columns in python
is Given Below:

I have a data frame where each level in column ‘a’ has a grouping factor in the ‘group’ column. I wonder whether there is a way to forward fill the ‘group’ column based on matching values, but without overtly specifying the exact number-string pair. I can remap by combining map and combine_first but I wonder if there is a more dynamic approach

Any tips are welcome thanks so much!

the pairs are as follows for column ‘a’ and ‘group’

  • 10 and 15 = group1
  • 20 = group 3
  • 25 = group2
df = pd.DataFrame({ 'a': [10, 15, 20, 25, 15, 10, 20, 10, 25], 'group': ['group1', np.nan, np.nan, 'group2', 'group1', np.nan, 'group3', np.nan, np.nan]})

and here is the remapping with a manually created map

dic = {10: "group1", 15: "group1", 20: "group3", 25: "group2"}
df.group = df.a.map(dic).combine_first(df.group)

You can try to create mapping Series dynamically:

df["group"] = df["a"].map(df.groupby("a")["group"].first())
print(df)

Prints:

    a   group
0  10  group1
1  15  group1
2  20  group3
3  25  group2
4  15  group1
5  10  group1
6  20  group3
7  10  group1
8  25  group2