English 中文(简体)
Python Polars - conditional join on value between other columns
原标题:

I have a Polars DataFrame that looks like this:

┌────────────┬───────┐
│ date       ┆ value │
│ ---        ┆ ---   │
│ str        ┆ i64   │
╞════════════╪═══════╡
│ 2022-01-01 ┆ 3     │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 2022-01-02 ┆ 7     │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ 2022-01-03 ┆ 12    │
└────────────┴───────┘

I have another DataFrame that looks like this:

┌──────────┬───────┬───────┐
│ category ┆ lower ┆ upper │
│ ---      ┆ ---   ┆ ---   │
│ str      ┆ i64   ┆ i64   │
╞══════════╪═══════╪═══════╡
│ A        ┆ 0     ┆ 5     │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ B        ┆ 5     ┆ 10    │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ C        ┆ 10    ┆ 15    │
└──────────┴───────┴───────┘

I want to join these two DataFrames so that the first DataFrame has a new column "category" where each row is categorized based on which category it falls between in the second DataFrame. The final DF should look something like this:

┌────────────┬───────┬──────────┐
│ date       ┆ value ┆ category │
│ ---        ┆ ---   ┆ ---      │
│ str        ┆ i64   ┆ str      │
╞════════════╪═══════╪══════════╡
│ 2022-01-01 ┆ 3     ┆ A        │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 2022-01-02 ┆ 7     ┆ B        │
├╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┤
│ 2022-01-03 ┆ 12    ┆ C        │
└────────────┴───────┴──────────┘

Is there a way to do this efficiently using Polars? What about with an unlimited upper bound on category C?

问题回答

If you have many categories in your second dataframe, you can "convert" it to SQL CASE expression:

cond = df_pl2.select(
    pl.format(
        "WHEN value >= {} AND value < {} THEN  {} ",
        pl.col("lower"),
        pl.col("upper"),
        pl.col("category"),
    ).alias("cond")
)
cond = "
".join(cond["cond"]) + " ELSE  Not Found "

The cond now contains:

WHEN value >= 0 AND value < 5 THEN  A 
WHEN value >= 5 AND value < 10 THEN  B 
WHEN value >= 10 AND value < 15 THEN  C  ELSE  Not Found 

Then use Polars SQLContext():

ctxt = pl.SQLContext()
ctxt.register("df_pl", df_pl.lazy())  # <-- `df_pl` is your first dataframe

print(
    ctxt.execute(
        f"""
    SELECT date, value,
    CASE
        {cond}
    END AS category
    FROM df_pl
""",
        eager=True,
    )
)

Prints:

┌────────────┬───────┬──────────┐
│ date       ┆ value ┆ category │
│ ---        ┆ ---   ┆ ---      │
│ str        ┆ i64   ┆ str      │
╞════════════╪═══════╪══════════╡
│ 2022-01-01 ┆ 3     ┆ A        │
│ 2022-01-02 ┆ 7     ┆ B        │
│ 2022-01-03 ┆ 12    ┆ C        │
└────────────┴───────┴──────────┘

If you want unlimited upper bound just update the last condition in the CASE statement, for example cond = cond.replace("AND value < 15", "")

join_asof is best for this "nearest key" type of problem. There are forward/backward join strategies:

df = pl.DataFrame({ value : [3, 7, 12]}).set_sorted( value )
df2 = pl.DataFrame({ category : [ A ,  B ,  C ],  lower : [0, 5, 10],  upper : [5, 10, 15]}).set_sorted([ lower ,  upper ])

df.join_asof(df2, left_on= value , right_on= lower , strategy= backward )
# equivalent alternate way, although the above is better for "unlimited upper bound"
df.join_asof(df2, left_on= value , right_on= upper , strategy= forward )
shape: (3, 4)
┌───────┬──────────┬───────┬───────┐
│ value ┆ category ┆ lower ┆ upper │
│ ---   ┆ ---      ┆ ---   ┆ ---   │
│ i64   ┆ str      ┆ i64   ┆ i64   │
╞═══════╪══════════╪═══════╪═══════╡
│ 3     ┆ A        ┆ 0     ┆ 5     │
│ 7     ┆ B        ┆ 5     ┆ 10    │
│ 12    ┆ C        ┆ 10    ┆ 15    │
└───────┴──────────┴───────┴───────┘

Alternatively, you could do a cut expression instead of any type of join:

df = pl.DataFrame({ value  : [3, 7, 12, 99]})
df2 = pl.DataFrame({ lower  : [0, 5, 10],  upper  : [5, 10, 15]})

df.with_columns(
    category=pl.col( value ).cut(
        df2.get_column( upper ), labels=[ A ,  B ,  C ,  unlimited ]
    )
)
shape: (4, 2)
┌───────┬───────────┐
│ value ┆ category  │
│ ---   ┆ ---       │
│ i64   ┆ cat       │
╞═══════╪═══════════╡
│ 3     ┆ A         │
│ 7     ┆ B         │
│ 12    ┆ C         │
│ 99    ┆ unlimited │
└───────┴───────────┘




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签