首页 > 解决方案 > 熊猫在数据框中第一次出现值

问题描述

我正在为我正在构建的应用程序抽象出很多 pandas 功能。我有一个场景,我需要从目标列中获取值,其中第一次出现的未知数条件评估为真。所以是这样的:

import pandas as pd

#lets say this dataframe already has data in it with column names and number index rows.
df = pd.Dataframe()

targetCols:list = [targetColName1, targetColName2]
compCols:list = [compColName1, compColName2]
compVals:list = [compVals1, compVals2]

#Some function that concatenates the compCols and compValues in to stirngs
# look like:
#  (f"(df[['{compCols[0]}']=={compVals[0]}]) & "
#   f"(df[['{compCols[1]}'] == {compVals[1]})")
strExeString = ConcatenateExecutonString(compCols, compVals)

dfView = pd.eval(strExeString)
dfView = dfView[targetCols]
return dfview.loc[0:]

然而,上面导致我扫描数据集很多,我想简单地扫描 DataFrame 一次,直到满足我的条件,然后提取目标列。我们可以用熊猫做到这一点吗?我可以使用本机列表对象来做到这一点,但如果我可以使用 pandas,我想这样做,因为它可以更有效地处理大型集合。

标签: pythonpandas

解决方案


推荐阅读