Например, если я начну с DataFrames main_pl (со всеми записями) и sub_pl (с подмножеством записей):
sub_pl (с подмножеством записей):
sub_pl (с подмножеством записей)
Код: Выделить всё
import polars as pl
r1 = {"foo":"a", "bar":"b", "baz":"c"}
r2 = {"foo":"x", "bar":"y", "baz":"z"}
r3 = {"foo":"a", "bar":"b", "baz":None}
r4 = {"foo":"m", "bar":"n", "baz":"o"}
r5 = {"foo":"x", "bar":"y", "baz":None}
r6 = {"foo":"a", "bar":"b", "baz":None}
all_records = [r1, r2, r3, r4, r5, r6]
sub_records = [r1, r2, r3]
target_cols = ["foo", "bar", "baz"]
main_pl = pl.DataFrame(all_records)
sub_pl = pl.DataFrame(sub_records)
Код: Выделить всё
shape: (6, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ baz │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪══════╡
│ a ┆ b ┆ c │
│ x ┆ y ┆ z │
│ a ┆ b ┆ null │
│ m ┆ n ┆ o │
│ x ┆ y ┆ null │
│ a ┆ b ┆ null │
└─────┴─────┴──────┘
Код: Выделить всё
shape: (3, 3)
┌─────┬─────┬──────┐
│ foo ┆ bar ┆ baz │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪══════╡
│ a ┆ b ┆ c │
│ x ┆ y ┆ z │
│ a ┆ b ┆ null │
└─────┴─────┴──────┘
< /code>
for_matching = sub_pl.select(
pl.struct(pl.col(target_cols)).alias("for_matching")
).get_column("for_matching")
for_matching
< /code>
shape: (3,)
Series: 'for_matching' [struct[3]]
[
{"a","b","c"}
{"x","y","z"}
{"a","b",null}
]
< /code>
[b]1.[/b] When comparing None
Код: Выделить всё
main_pl.with_columns(
pl.struct(pl.all()).is_in(for_matching.implode()).alias("matched"))
< /code>
shape: (6, 4)
┌─────┬─────┬──────┬─────────┐
│ foo ┆ bar ┆ baz ┆ matched │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ bool │
╞═════╪═════╪══════╪═════════╡
│ a ┆ b ┆ c ┆ true │
│ x ┆ y ┆ z ┆ true │
│ a ┆ b ┆ null ┆ true │
│ m ┆ n ┆ o ┆ false │
│ x ┆ y ┆ null ┆ false │
│ a ┆ b ┆ null ┆ true │
└─────┴─────┴──────┴─────────┘
< /code>
--- join
Код: Выделить всё
main_pl.join(sub_pl, on=target_cols)
< /code>
shape: (2, 3)
┌─────┬─────┬─────┐
│ foo ┆ bar ┆ baz │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪═════╡
│ a ┆ b ┆ c │
│ x ┆ y ┆ z │
└─────┴─────┴─────┘
< /code>
[b]2.[/b] Is there a way to make polars is_in
Код: Выделить всё
import pandas as pd
main_pd = pd.DataFrame(all_records)
sub_pd = pd.DataFrame(sub_records)
main_pd["matched_w_none"] = main_pd[target_cols].isin(sub_pd).all(1)
pl.from_pandas(main_pd)
< /code>
shape: (6, 4)
┌─────┬─────┬──────┬────────────────┐
│ foo ┆ bar ┆ baz ┆ matched_w_none │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ bool │
╞═════╪═════╪══════╪════════════════╡
│ a ┆ b ┆ c ┆ true │
│ x ┆ y ┆ z ┆ true │
│ a ┆ b ┆ null ┆ false │
│ m ┆ n ┆ o ┆ false │
│ x ┆ y ┆ null ┆ false │
│ a ┆ b ┆ null ┆ false │
└─────┴─────┴──────┴────────────────┘
< /code>
[b]Ultimately[/b] I'm trying to achieve the same results through polars that I get by default with pandas when comparing rows from different dataframes where None
Подробнее здесь: https://stackoverflow.com/questions/796 ... hon-polars