首页 > 解决方案 > 追加 DataFrame 并在 for 循环中添加条件

问题描述

我正在尝试使用条件返回数据框。当以下示例中存在身高和体重等两个特征时,如何处理该条件,因为我的代码现在通过替换前一个条件仅采用第二个条件。df['conditions'] 值如下:height <= 9.10 & weight <= 89

现在它只在返回时执行以下操作:

df_store_cond1 = df_store.loc[(df_store[weight] <= float(89))]

但是,在返回数据框之前,我想要执行以下操作,以便检查两个条件:

df_store_cond1 = df_store.loc[(df_store[weight] <= float(89)) & (df_store[height] <= float(9.10))]

def func(sno): 
    df_store = X_train.copy()  #copying the dataframe to another df
    features = features_list = df['conditions'].tolist()[int(sno)]
    if '&' in features:
        if '&' and '<=' in features:
            for k in features.split('&'):
                print(features)
                j = k.replace(' ','')
                if '<=' in j:
                    operator1 = j.split('<=')
                df_store_cond1 = df_store.loc[(df_store[str(operator1[0])] <= float(operator1[1]))]
            return df_store_cond1        

标签: python

解决方案


您的代码创建新df_store_cond1的每个 for 循环。尝试像这样更新您的代码:

def func(sno): 
    df_store = X_train.copy()  #copying the dataframe to another df
    features = features_list = df['conditions'].tolist()[int(sno)]
    if '&' in features:
        if '&' and '<=' in features:
            for k in features.split('&'):
                print(features)
                j = k.replace(' ','')
                if '<=' in j:
                    operator1 = j.split('<=')
                df_store = df_store.loc[(df_store[str(operator1[0])] <= float(operator1[1]))]
            return df_store 

推荐阅读