筛选值并将结果合并为一体

yqlxgs2m  于 2022-09-21  发布在  其他
关注(0)|答案(1)|浏览(124)

我列出了多个 Dataframe ,并尝试根据条件过滤一列中的多个值。

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
niwlg2el

niwlg2el1#

您可以对代码进行一些改进。首先,不要使用list作为您的变量,因为它已经是Python中的内置函数。其次,您始终可以创建结果列表,然后将其添加回列中。

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

相关问题