Question:
How to use `isin` in Polars DataFrame?

In Polars, you can use the is_in method to check if a column's values are contained within a list of values. Here's how you can use is_in in a Polars DataFrame:

import polars as pl


# Create a sample DataFrame

df.with_columns(pl.col("A").is_in(my_list))


# Define a list of values to check against

values_to_check = [2, 4, 6]


# Use `is_in` to check if the values in column 'A' are in the list

result = df.select(df['A'].is_in(values_to_check).alias('is_in_values'))


# Display the result

print(result)


The output will be:

shape: (5, 1)

┌───────┐

│ A     │

│ ---   │

│ bool  │

╞═══════╡

│ true  │

│ false │

│ false │

│ null  │

│ true  │

└───────┘


In the result DataFrame, the is_in_values column indicates whether each value in column 'A' is present in the values_to_check list.


You can also use is_in with string columns:

# Use `is_in` to check if the values in column 'B' are in the list

result = df.select(df['B'].is_in(['foo', 'qux', 'corge']).alias('is_in_values'))


# Display the result

print(result)


In this case the output will be:

shape: (5, 1)

┌─────────────┐

│ is_in_values│

│ ---         │

│ true        │

│ false       │

│ false       │

│ true        │

│ false       │

└─────────────┘



Credit: >Stack Overflow


Suggested blogs:

>How to create a line animation in Python?

>How to create a new/simple PHP script/function with cURL to upload simple file (video.mp4)?

>How to route between different components in React.js?

>How to save python yaml and load a nested class?-Python

>How to send multiple HTML form fields to PHP arrays via Ajax?

>What is data binding in Angular?

>How to create a One Page App with Angular.js, Node.js and MongoDB?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation


Ritu Singh

Ritu Singh

Submit
0 Answers