I am trying to do some column-wide multiplication and division in groups and join them together. But I'd like to do it at scale - currently it's a bit repetitive - columns with A string divide by columns with D string and multiply by WC column and then repeat a similar process on group columns B and C towards columns D and columns WC. At the end, I will merge them into the same dataframe. How can I make the process more efficient?
input:
df = pd.DataFrame({"cid" : {0 : "cd1", 1 : "cd2", 2 : "cd3"},
"A1970" : {0 : 3.2, 1 : 3.5, 2 : .4},
"A1980" : {0 : 3.1, 1 : 3.6, 2 : .5},
"B1970" : {0 : 2.5, 1 : 1.2, 2 : .7},
"B1980" : {0 : 3.2, 1 : 1.3, 2 : .1},
"C1970" : {0 : 3.2, 1 : 3.3, 2 : .3},
"C1980" : {0 : 3.3, 1 : 3.4, 2 : .3},
"D1970" : {0 : 2.4, 1 : 1.3, 2 : .7},
"D1980" : {0 : 3.2, 1 : 1.3, 2 : .2},
"WC" : {0 :0.5, 1 : 0.3, 2 : .1}
}).set_index(['cid'])
# A1970 A1980 B1970 B1980 C1970 C1980 D1970 D1980 WC
# cid
# cd1 3.2 3.1 2.5 3.2 3.2 3.3 2.4 3.2 0.5
# cd2 3.5 3.6 1.2 1.3 3.3 3.4 1.3 1.3 0.3
# cd3 0.4 0.5 0.7 0.1 0.3 0.3 0.7 0.2 0.1
processing:
df_a = (df.filter(regex='A')
.div(df.filter(regex='D').values)
.multiply(df["WC"], axis="index")
.add_suffix("_rt"))
# A1970_rt A1980_rt
# cid
# cd1 0.666667 0.484375
# cd2 0.807692 0.830769
# cd3 0.057143 0.250000
df_b = (df.filter(regex='B')
.div(df.filter(regex='D').values)
.multiply(df["WC"], axis="index")
.add_suffix("_rt"))
df_c = (df.filter(regex='C')
.div(df.filter(regex='D').values)
.multiply(df["WC"], axis="index")
.add_suffix("_rt"))