2

In polars pandas want to inter change/ assign , & inter change row value in two rows.

for i in range(len(k2)):
    k2['column1'][i] == k2['column2'][i]
    k2['column3'][i] == k2['column4'][i]
1
  • k2.with_columns([pl.col("column1").alias("column3"),pl.col("column3").alias("column1")]) may be helpful. Commented May 9, 2022 at 1:48

1 Answer 1

3

You can use alias to copy & rename columns:

import polars as pl

k2 = pl.DataFrame({"column1": [1,2,3],
                   "column2": [4,5,6],
                   "column3": [7,8,9],
                   "column4": [10,11,12]})

┌─────────┬─────────┬─────────┬─────────┐
│ column1 ┆ column2 ┆ column3 ┆ column4 │
│ ---     ┆ ---     ┆ ---     ┆ ---     │
│ i64     ┆ i64     ┆ i64     ┆ i64     │
╞═════════╪═════════╪═════════╪═════════╡
│ 1       ┆ 4       ┆ 7       ┆ 10      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 2       ┆ 5       ┆ 8       ┆ 11      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 3       ┆ 6       ┆ 9       ┆ 12      │
└─────────┴─────────┴─────────┴─────────┘
k2.with_columns([pl.col("column2").alias("column1"), pl.col("column4").alias("column3")])

which prints out

┌─────────┬─────────┬─────────┬─────────┐
│ column1 ┆ column2 ┆ column3 ┆ column4 │
│ ---     ┆ ---     ┆ ---     ┆ ---     │
│ i64     ┆ i64     ┆ i64     ┆ i64     │
╞═════════╪═════════╪═════════╪═════════╡
│ 4       ┆ 4       ┆ 10      ┆ 10      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 5       ┆ 5       ┆ 11      ┆ 11      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 6       ┆ 6       ┆ 12      ┆ 12      │
└─────────┴─────────┴─────────┴─────────┘
Sign up to request clarification or add additional context in comments.

1 Comment

I got something like we can filter data frame features and store in a new variable then swap like :- k2['col1'] = k2['col3'] k2['col2'] = k2['col4']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.