<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Advanced Topics
Step1:  Using scalar aggregates in filters
Step2:  We could always compute some aggregate value from the table and use that in another expression, or we can use a data-derived aggregate in the filter. Take the average of a column for example
Step3:  You can use this expression as a substitute for a scalar value in a filter, and the execution engine will combine everything into a single query rather than having to access Impala multiple times
Step4:  Conditional aggregates
Suppose that we wish to filter using an aggregate computed conditional on some other expressions holding true. Using the TPC-H datasets, suppose that we want to filter customers based on the following criteria
Step5:  In this particular case, filtering based on the conditional average o_totalprice by region requires creating a table view (similar to the self-join examples from earlier) that can be treated as a distinct table entity in the expression. This would not be required if we were computing a conditional statistic from some other table. So this is a little more complicated than some other cases would be
Step6:  Once you've done this, you can use the conditional average in a filter expression
Step7:  By looking at the table sizes before and after applying the filter you can see the relative size of the subset taken.
Step8:  Or even group by year and compare before and after
Step9:  "Existence" filters
Some filtering involves checking for the existence of a particular value in a column of another table, or amount the results of some value expression. This is common in many-to-many relationships, and can be performed in numerous different ways, but it's nice to be able to express it with a single concise statement and let Ibis compute it optimally.
Here's some examples
Step10:  We introduce the any reduction
Step11:  This is now a valid filter
Step12:  For the second example, in which we want to find customers not having any open urgent orders, we write down the condition that they do have some first
Step13:  Now, we can negate this condition and use it as a filter
<ASSISTANT_TASK:>
Python Code:
import ibis
import os
hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070)
hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port)
con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing',
                          hdfs_client=hdfs)
ibis.options.interactive = True
Explanation: Advanced Topics: Additional Filtering
The filtering examples we've shown to this point have been pretty simple, either comparisons between columns or fixed values, or set filter functions like isin and notin. 
Ibis supports a number of richer analytical filters that can involve one or more of:
Aggregates computed from the same or other tables
Conditional aggregates (in SQL-speak these are similar to "correlated subqueries")
"Existence" set filters (equivalent to the SQL EXISTS and NOT EXISTS keywords)
Setup
End of explanation
table = con.table('functional_alltypes')
table.limit(5)
Explanation: Using scalar aggregates in filters
End of explanation
table.double_col.mean()
Explanation: We could always compute some aggregate value from the table and use that in another expression, or we can use a data-derived aggregate in the filter. Take the average of a column for example:
End of explanation
cond = table.bigint_col > table.double_col.mean()
expr = table[cond & table.bool_col].limit(5)
expr
Explanation: You can use this expression as a substitute for a scalar value in a filter, and the execution engine will combine everything into a single query rather than having to access Impala multiple times:
End of explanation
region = con.table('tpch_region')
nation = con.table('tpch_nation')
customer = con.table('tpch_customer')
orders = con.table('tpch_orders')
fields_of_interest = [customer,
                      region.r_name.name('region'), 
                      orders.o_totalprice,
                      orders.o_orderdate.cast('timestamp').name('odate')]
tpch = (region.join(nation, region.r_regionkey == nation.n_regionkey)
        .join(customer, customer.c_nationkey == nation.n_nationkey)
        .join(orders, orders.o_custkey == customer.c_custkey)
        [fields_of_interest])
tpch.limit(5)
Explanation: Conditional aggregates
Suppose that we wish to filter using an aggregate computed conditional on some other expressions holding true. Using the TPC-H datasets, suppose that we want to filter customers based on the following criteria: Orders such that their amount exceeds the average amount for their sales region over the whole dataset. This can be computed any numbers of ways (such as joining auxiliary tables and filtering post-join)
Again, from prior examples, here are the joined up tables with all the customer data:
End of explanation
t2 = tpch.view()
conditional_avg = t2[(t2.region == tpch.region)].o_totalprice.mean()
Explanation: In this particular case, filtering based on the conditional average o_totalprice by region requires creating a table view (similar to the self-join examples from earlier) that can be treated as a distinct table entity in the expression. This would not be required if we were computing a conditional statistic from some other table. So this is a little more complicated than some other cases would be:
End of explanation
amount_filter = tpch.o_totalprice > conditional_avg
tpch[amount_filter].limit(10)
Explanation: Once you've done this, you can use the conditional average in a filter expression
End of explanation
tpch.count()
tpch[amount_filter].count()
Explanation: By looking at the table sizes before and after applying the filter you can see the relative size of the subset taken.
End of explanation
tpch.schema()
year = tpch.odate.year().name('year')
pre_sizes = tpch.group_by(year).size()
post_sizes = tpch[amount_filter].group_by(year).size().view()
percent = ((post_sizes['count'] / pre_sizes['count'].cast('double'))
           .name('fraction'))
expr = (pre_sizes.join(post_sizes, pre_sizes.year == post_sizes.year)
        [pre_sizes.year, 
         pre_sizes['count'].name('pre_count'),
         post_sizes['count'].name('post_count'),
         percent])
expr
Explanation: Or even group by year and compare before and after:
End of explanation
customer = con.table('tpch_customer')
orders = con.table('tpch_orders')
orders.limit(5)
Explanation: "Existence" filters
Some filtering involves checking for the existence of a particular value in a column of another table, or amount the results of some value expression. This is common in many-to-many relationships, and can be performed in numerous different ways, but it's nice to be able to express it with a single concise statement and let Ibis compute it optimally.
Here's some examples:
Filter down to customers having at least one open order
Find customers having no open orders with 1-URGENT status
Find stores (in the stores table) having the same name as a vendor (in the vendors table).
We'll go ahead and solve the first couple of these problems using the TPC-H tables to illustrate the API:
End of explanation
has_open_orders = ((orders.o_orderstatus == 'O') & 
                   (customer.c_custkey == orders.o_custkey)).any()
Explanation: We introduce the any reduction:
End of explanation
customer[has_open_orders].limit(10)
Explanation: This is now a valid filter:
End of explanation
has_open_urgent_orders = ((orders.o_orderstatus == 'O') & 
                          (orders.o_orderpriority == '1-URGENT') & 
                          (customer.c_custkey == orders.o_custkey)).any()
Explanation: For the second example, in which we want to find customers not having any open urgent orders, we write down the condition that they do have some first:
End of explanation
customer[-has_open_urgent_orders].count()
Explanation: Now, we can negate this condition and use it as a filter:
End of explanation
<END_TASK>