Esto logra lo que quieres, y funciona con cualquiera cantidad de Zone1
, Zone2
, ..., ZoneN
:
import pandas as pd
d = {"ID": [1,1,3,3,5],
"Zone1": ["R5B","C2","C2","C1","M1-5"],
"Valor1": [10,20,4,8,6],
"Zone2": ["C2","M2-6","C4","0","M2-6"],
"Valor2": [20,6,6,0,15],
"Zone3": ["R10A","R5B","0","0","0"],
"Valor3": [5,3,0,0,0]}
df = pd.DataFrame(data=d)
headers = list(df)
headers.sort()
valors = [h for h in headers if h.startswith("Valor")]
zones = [h for h in headers if h.startswith("Zone")]
rc = ["R","C"]
m = ["M"]
# Si ZonaX empieza por 'R' o 'C', sumará ValorX
df["total"] = sum(df[zone].str[0].isin(rc) * df[valor]
for zone, valor in zip(zones, valors))
# Si ZonaX empieza por 'M', sumará ValorX
df["total1"] = sum(df[zone].str[0].isin(m) * df[valor]
for zone, valor in zip(zones, valors))
<! >
print(df)
ID Zone1 Valor1 Zone2 Valor2 Zone3 Valor3 total total1
0 1 R5B 10 C2 20 R10A 5 35 0
1 1 C2 20 M2-6 6 R5B 3 23 6
2 3 C2 4 C4 6 0 0 10 0
3 3 C1 8 0 0 0 0 8 0
4 5 M1-5 6 M2-6 15 0 0 0 21