import pandas as pd
#create df with values that do not equal total
df = pd.DataFrame({'Residential':[5, 10, 15, 20],
'Commercial':[5, 10, 15, 20],
'Total':[10, 20, 30, 50]})
# Create an empty list
Row_list = []
# Iterate over each row
for index, rows in df.iterrows():
# Create list for the current row
my_list = [rows.Residential, rows.Commercial, rows.Total]
# append the list to the final list
Row_list.append(my_list)
#find which columns do not add to total and remove them
for i, x in enumerate(Row_list):
if x[0] + x[1] != x[2]:
Row_list.remove(x)
#transpose back into correct format of rows and columns
Column_list = [list(x) for x in zip(*Row_list)]
#create new df
new_df = pd.DataFrame({'Residential':Column_list[0],
'Commercial':Column_list[1],
'Total':Column_list[2]})
#print
print(new_df)
это довольно длинный способ сделать это, но шаг за шагом показывает процесс