python - 追加 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
解决方案
您的代码创建新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
推荐阅读
- android - 从新代码控制 AOSP 功率报告功能
- google-analytics - Google 分析报告 API 通过分页返回不正确的数据
- java - Android工作室中的重复类冲突
- typescript - 排序导入 - 排序导入,从命名空间导入
- android - 如何更改 Android Studio 中主文件夹的默认位置
- powershell - 提取有关 WMI 查询的一些信息并返回此信息
- javascript - Javascript 类型的 VSCode 扩展
- excel - 复制和粘贴时跳过列的代码
- python - 从 HSV 颜色空间转换的 RGB 图像的颜色图
- c++ - 从 WindowsAPI 调用 NetLocalGroupAddMembers 时,安全 ID 结构无效错误