polars.DataFrame.__setitem__#

DataFrame.__setitem__(
key: str | Sequence[int] | Sequence[str] | tuple[Any, str | int],
value: Any,
) None[source]#

Modify DataFrame elements in place, using assignment syntax.

Parameters:
keystr | Sequence[int] | Sequence[str] | tuple[Any, str | int]

Specifies the location(s) within the DataFrame to assign new values. The behavior varies based on the type of key:

  • Str: df["a"] = value:

    Not supported. Raises a TypeError. Use df.with_columns(...) to add or modify columns.

  • Sequence[str]: df[["a", "b"]] = value:

    Assigns multiple columns at once. value must be a 2D array-like structure with the same number of columns as the list of column names provided.

  • tuple[Any, str | int]: df[row_idx, "a"] = value:

    Assigns a new value to a specific element in the DataFrame, where row_idx specifies the row and "a" specifies the column.

  • df[row_idx, col_idx] = value:

    Similar to the above, but col_idx is the integer index of the column.

valueAny

The new value(s) to assign. The expected structure of value depends on the form of key:

  • For multiple column assignment (df[["a", "b"]] = value), value should be a 2D array-like object with shape (n_rows, n_columns).

  • For single element assignment (df[row_idx, "a"] = value), value should be a scalar.

Raises:
TypeError

If an unsupported assignment is attempted, such as assigning a Series directly to a column using df["a"] = series.

ValueError

If the shape of value does not match the expected shape based on key.

Examples

Sequence[str] : df[["a", "b"]] = value:

>>> import numpy as np
>>> df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
>>> df[["a", "b"]] = np.array([[10, 40], [20, 50], [30, 60]])
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10  ┆ 40  │
│ 20  ┆ 50  │
│ 30  ┆ 60  │
└─────┴─────┘

tuple[Any, str | int] : df[row_idx, "a"] = value:

>>> df[1, "a"] = 100
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10  ┆ 40  │
│ 100 ┆ 50  │
│ 30  ┆ 60  │
└─────┴─────┘

df[row_idx, col_idx] = value:

>>> df[0, 1] = 30
>>> df
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 10  ┆ 30  │
│ 100 ┆ 50  │
│ 30  ┆ 60  │
└─────┴─────┘