'python dataframe using nested for loop to get cost sum for flagged combination of 2 columns

Supposed this is the first 3 rows of the dataset, rest looks similar. And there can be more than 3 books. lets say 6 books.

a=[['a',1,1,0,123],['b',1,0,1,153],['c',0,1,1,126]] 
df= pd.DataFrame(a,columns=['id','book1','book2','book3','cost']) 
print(df)

id  book_1  book_2  book_3  cost
a   1         1      0      123
b   1         0      1      154
c   0         1      1      159

I want to have a nested for loop (or anything, I can only think of for loop) to get the sum of cost. The desired progress should be like I want the sum of cost of in row where (book1 and book2 ==1) , then the for loop will continue to (book1 and book3 ==1), until (book1 and bookN ==1) is finished. then start (book2 and book3 ==1) until (book2 and bookN ==1) is finished. And repeat the process



Solution 1:[1]

I think this is what you are after:

df["Total"] = df["cost"] * (df["book1"]+df["book2"]+df["book3"])
df["Total"].sum()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dominic Johnston Whiteley