Das ist meine Funktion:
Code: Select all
import polars as pl
def clean_data(df, cols):
return (
df.with_columns(pl.mean(col).alias(f"__{col}_mean") for col in cols)
.with_columns(
pl.when(pl.col(col) < pl.col(f"__{col}_mean") * 3 / 4)
.then(pl.col(f"__{col}_mean") * 3 / 4)
.when(pl.col(col) > pl.col(f"__{col}_mean") * 5 / 4)
.then(pl.col(f"__{col}_mean") * 5 / 4)
.otherwise(pl.col(col))
.alias(col)
for col in cols
)
.select(pl.exclude(f"__{col}_mean" for col in cols))
)
Code: Select all
df = pl.DataFrame(
{
"a": [1, 2, 3, 4, 5, 12, 28],
"a2": [1, 2, 3, 4, 5, 6, 7],
}
)
clean_data(df, ["a", "a2"])
Code: Select all
shape: (7, 2)
┌──────────┬─────┐
│ a ┆ a2 │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞══════════╪═════╡
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 4.0 │
│ 5.892857 ┆ 5.0 │
│ 9.821429 ┆ 5.0 │
│ 9.821429 ┆ 5.0 │
└──────────┴─────┘
Code: Select all
df = pl.DataFrame(
{
"a": [1, 2, 3, 4, 5, 12, 28],
"a2": [1, 2, 3, 4, 5, 6, 7],
"__a_mean": [1, 1, 1, 1, 1, 1, 1],
}
)
clean_data(df, ["a", "a2"])
Code: Select all
shape: (7, 2)
┌──────────┬─────┐
│ a ┆ a2 │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞══════════╪═════╡
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 3.0 │
│ 5.892857 ┆ 4.0 │
│ 5.892857 ┆ 5.0 │
│ 9.821429 ┆ 5.0 │
│ 9.821429 ┆ 5.0 │
└──────────┴─────┘
Gibt es eine Möglichkeit, temporäre Spalten mitten in Berechnungen anzuhängen und sicherzustellen, dass generierte temporäre Spaltennamen nicht im ursprünglichen DataFrame vorhanden sind?
Gibt es alternativ eine Möglichkeit, meine obige Funktion zu implementieren, ohne Ergebnisse zwischenzuspeichern und ohne Leistungseinbußen zu machen?
Mobile version