I'm working with a data framework like this, but bigger and with more areas. I'm trying to add the value of the rows by their names. This is my code but I get an error. The total of the sums of the R or C zones go in the column total
and the total of the sums of the zones M goes in the column total1
.
"C1" does not appear in the list.
This happens because the program is trying to add the value of C1 when it finds any other value that makes the condition of If
statement true.
Marco:
ID Zone1 CHC1 Valor1 Zone2 CHC2 Valor2 Zone3 CHC3 Valor3 total total1
1 R5B 100 10 C2 0 20 R10A 2 5 35 0
1 C2 95 20 M2-6 5 6 R5B 7 3 23 6
3 C2 40 4 C4 60 6 0 6 0 10 0
3 C1 100 8 0 0 0 0 100 0 8 0
5 M1-5 10 6 M2-6 86 15 0 0 0 0 21
Code:
import pandas as pd
df = pd.read_excel("C:PATH")
total = []
total1 = []
for i in range(df.shape[0]):
temp = df.iloc[i].tolist()
if ("R5B" in temp) |("R10A" in temp) | ("C2" in temp) | ("C1" in temp) | ("C4" in temp) :
total.append(temp[temp.index("R5B")+2] + temp[temp.index("R10A")+2] +temp[temp.index("C2")+2] + temp[temp.index("C1")+2] +temp[temp.index("C4")+2])
if ("M1-5" in temp) | ("M2-6" in temp):
total1.append(temp[temp.index("M1-5")+2] + temp[temp.index("M2-6")+2])
df["Total"] = total
df["Total1"] = total1
print (df)