python - 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 很灵活,如果您也有更好的想法,我可以更改它的外观/工作方式。例如,也许传入一个运算符函数不是最好的主意。
解决方案
让我们尝试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
推荐阅读
- python - Django 数据库 - lastrowid
- oracle - 无法为给定场景创建 Oracle 函数
- python - 将列表的值与具有信誉的同一列表中的其他值进行比较
- xamarin.forms - 当 CollectionView 包含在 ScrollView 中并且 ScrollView 的 Visible 为 False 时,Xamarin 应用程序无法启动
- javascript - 如何正确使用 AntD FormInstance 函数?
- javascript - javascript如何实现对window.location对象的赋值操作
- css - 如何使标记在任何地方都相同并使数字居中?
- php - Laravel 雄辩的关系与数据库查询
- mysql - 表约束——mysql中的主键
- python - 如何在pytorch中改变NN的权重