【问题标题】:How to filter a DataFrame by a function如何通过函数过滤 DataFrame
【发布时间】:2021-10-17 17:55:54
【问题描述】:

我想使用传递我创建的函数的条件来过滤 DataFrame。此函数将返回 True 或 False。

但我得到了这个例外:

TypeError: 无法将系列转换为

这是我的代码:

def filter():
    inicio = time.time()
    df = pd.read_csv('data_base.csv')
    nrows = df.shape[0]
    for i in range(nrows).__reversed__():
        coincidencias = df[
            (df['Fecha'] == df.loc[i]['Fecha']) &
            (df['Mercado'] == df.loc[i]['Mercado']) &
            (df['Local'].str.contains(main_word(df.loc[i]['Local']), case=False)) &
            (df['Visitante'].str.contains(main_word(df.loc[i]['Visitante']), case=False)) &
     ---->  (is_there_surebet(df['Contenido'], df.loc[i]['Contenido']))   <----
            ].dropna()

        if coincidencias.shape[0] > 1:
            print(coincidencias)


        df = df.drop([i])
    fin = time.time()
    print(fin-inicio)

箭头之间的线是导致异常的线。让我知道is_there_surebet 函数是否是解决问题所必需的,但我认为情况并非如此。

【问题讨论】:

    标签: python dataframe filter


    【解决方案1】:

    这个想法是创建一个返回 True \ False 的函数并将其应用于相关列。请检查以下示例是否有帮助 -

    def my_filter(x):
        return x > 0
    
    df = pd.DataFrame({"x": [1, 2, 3, -4, 5, -3], "y": ["a", "b", "c", "d", "e", "f"]})
    df[df["x"].apply(my_filter)]
    

    结果将仅是x 列中的值大于 0 的行。

    对于需要从多列输入的更复杂的东西,您可以使用这样的东西 -

    def my_filter(record):
        if record["x"] < 0:
            return False
        return record["y"] in ["a", "b", "c"]
    
    df[df.apply(my_filter, axis=1)]
    

    编辑 - 添加更多示例

    如果你想使用一个参数,你可以这样做 -

    def my_filter(record, my_param):
        if record["x"] < my_param:
            return False
        return record["y"] in ["a", "b", "c"]
    
    df[df.apply(lambda x: my_filter(x, 5), axis=1)]
    

    【讨论】:

    • 我以前看到过类似的东西。但不幸的是,这不是我想要的。我想知道 DataFrame 类中是否有任何方法允许我将单元格作为参数传递。我举个例子。想象一下,我正在使用您刚刚定义的那个函数。但我不会将“0”作为参数传递,而是使用 DataFrame 中的另一个元素,例如 x > X_o,其中 X_o 是位置 (0,0) 中的元素。这真的可能吗?
    • 这个元素是在同一条记录中,即行还是其他地方?
    • 不在同一行或同一列但在同一Dataframe中
    • 所有行都一样吗?如果是这样,请提取它并将其用作参数。请看我刚刚添加的示例
    • 没关系,我想我想通了。但是非常感谢您的宝贵时间!
    猜你喜欢
    • 2022-11-15
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-02-13
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多