import pandas as pd
data = {'Region': ['A', 'A', 'B', 'B', 'C', 'C'],
'Description': ['D1', 'D2', 'D1', 'D2', 'D1', 'D2'],
'Baseline 1':[1,2,3,4,5,6]
:
'Baseline N': [some numbers]
'Regime 1': [0,0,0,0,2,3]
:
'Regime N': [some numbers]
}
df1 = pd.DataFrame(data)
replace_data = {'Region':['A','B','C'],
'Values':[6,7,8]}
df2 = pd.DataFrame(replace_data)
I have a dataframe which has 'Region' as index and need to replace all the regions where description is 'D2' and **Regime 1 to N having 0 ** (any regime like column having 0) with the 'replace_data' dataframe value of the particular region.
So Regime 1 from above code example should have final value as [0,6,0,7,2,3] (Notice 0 replaced by 6 & 7 from the replace_data frame for region A and B). For each regime column, this need to be done. Rest of the columns (like baseline) should remain as it is.
I can run a loop for all regime like columns and replace but I feel that will be very inefficient and time consuming since I have 20+ such columns and need to similar operations multiple time. Any efficient way to do this?
df.loc[((df['Description']=='D2'),regime_all_cols].replace({0:df2['Values'].values[0]})
This used to work when I had only 1 region but with multiple it doesn't work accurately.