首页 > 解决方案 > Pandas:根据以前未知数量的条件分配值

问题描述

我有一个接收 DataFrame 的函数,以及一个包含列名、运算符和阈值的字典。

函数看起来像:

df = pd.DataFrame(...)
df["passed_thresholds"] = False
threshold_dict = {"height": (operator.lt, 0.7), "width": (operator.gt, 0.1)}
def my_func(df, threshold_dict):
    # return df with "passed_thresholds" equal true for rows that meet the thresholds.

我想要做的是找到df满足阈值的所有行,threshold_dict并将“passed_thresholds”列设置为仅针对这些行。通常我可以很容易地做到这一点:

df.loc[(df["height"] < 0.7) & (df["width"] > 0.1), "passed_thresholds"] = True

但这里的问题是我不知道 threshold_dict 中有多少元素以及它们的值是什么。顺便说一句,threshold_dict 很灵活,如果您也有更好的想法,我可以更改它的外观/工作方式。例如,也许传入一个运算符函数不是最好的主意。

标签: pythonpandasnumpydataframe

解决方案


让我们尝试concat使用 for 循环然后应用all

out = pd.concat([y[0](df[x],y[1]) for x, y in threshold_dict.items()],axis=1).all(1)
df['passed_thresholds'] = out 

推荐阅读