【问题标题】:How to pass a "Take All" parameter in pandas loc filter condition?如何在 pandas loc 过滤条件中传递“Take All”参数?
【发布时间】:2019-11-20 22:41:12
【问题描述】:

我有一个带有参数的函数(在这种情况下:“部门”)从我的数据集中过滤(df.loc [(df ['A'] ==部门)特定数据。在一种情况下,我想要使用这个特定的功能,而不是过滤数据,我想获取所有数据。

有没有办法传递一个会导致类似的参数 df.loc[(df['A'] == *)df.loc[(df['A'] == %)

    # Write the data to the table 

    def table_creation(table, department, status):

        def condition_to_value(df, kpi):
            performance_indicator = df.loc[(df['A'] == department) & (df['C'] == kpi) & (df['B'] == status), 'D'].values[0]
        return performance_indicator

【问题讨论】:

    标签: python pandas pandas-loc


    【解决方案1】:

    我认为您不能通过像在 SQL 查询中那样传递参数来做到这一点。您必须稍微重写您的函数才能考虑到这种情况。

    【讨论】:

      【解决方案2】:

      我能想到的一种方法是,您可以使用df['A'].isin(['department']),而不是使用:df['A'] == 'department'。两者产生相同的结果。

      一旦你这样做了,你就可以像这样传递“Take All”参数:

      df['A'].isin(df['A'].unique())
      

      其中df['A'].unique() 是该列中所有唯一参数的列表,因此它将返回所有True

      或者你可以像这样传递多个参数:

      df['A'].isin(['department', 'string_2', 'string_3']))
      

      【讨论】:

        【解决方案3】:

        Newskooler's answer 的基础上构建,因为您知道要搜索的列的名称,您可以在函数中添加他的解决方案并相应地处理“*”。

        看起来像这样:

        # Write the data to the table 
        def table_creation(table, department, status):
            def condition_to_value(df, kpi):
                # use '*' to identify all departments
                if isinstance(department, str) and department=='*':
                    department = df['A'].isin(df['A'].unique()) 
                # make the function work with string or list inputs
                if isinstance(department, str):
                    department = [department, ]
                # notice the addition of the isin as recommended by Newskooler
                performance_indicator = df.loc[(df['A'].isin(department)) & (df['C'] == kpi) & (df['B'] == status), 'D'].values[0]
                return performance_indicator
        

        我意识到这里缺少部分,因为它们也在最初的问题中,但是这种更改应该可以工作,而无需更改您现在调用函数的方式,但将包括上一个答案中列出的好处。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-12
          • 1970-01-01
          • 2022-01-07
          • 2018-05-04
          • 1970-01-01
          • 2018-02-17
          相关资源
          最近更新 更多