Filtering value and combining results in one

Viewed 34

I've list of multiple dataframes and am trying to filter multiple values in a column based on a condition.

list = [df1,df2,df3,df4]             # multiple dataframes
grp_list = [con, eco, dip, pol]      # multiple categories in a column 

for i in list: 
if i['pgp'].isin(group_list) and (i.egp == i.pgp):
    i['value'] = 1
elif ~i['pgp'].isin(group):
    i['value'] = 2
else:
    0

df1:
pgp     egp     value
con     con      1     # return 1 if pgp value is in the element list & pgp = egp
eco     eco      1     
dip     health   0     # else 0
pol     health   0
god     con      2
ent     eco      2     # return 2 if pgp value is not in the element list
1 Answers

There are some improvements you can do to your code. Firstly, don't use list as your variable as it is already a built-in function in Python. Secondly, you can always create a list of result and then add it back into the column.

list_ = [df1,df2,df3,df4]             # multiple dataframes
grp_list = ['con', 'eco', 'dip', 'pol']      # multiple categories in a column 


for i in list_: 
    result = []
    for row_pgp, row_egp in zip(i['pgp'], i['egp']):
        if row_pgp in grp_list and row_pgp == row_egp:
            result.append(1)
        elif row not in grp_list and row_egp in grp_list:
            result.append(2)
        else:
            result.append(0)
    
    i['value'] = result
Related