Selecting a conditional column in SQL using CASE WHEN
, translated to pandas.
Selecting a column on a single condition
In SQL:
SELECT
column_1,
CASE WHEN column_2 > 10 THEN "Comment" ELSE "Other comment" END AS comment
FROM
table;
In pandas:
table
.assign(comment = table['column_1']
.apply(lambda column_1: 'Comment' if column_1 > 10 else 'Other comment'))
[['column_1', 'comment']]
Selecting a column on multiple conditions
In SQL:
SELECT
column_1,
CASE WHEN column_1 > 10 THEN "Comment" WHEN column_1 < 1 THEN "Other comment" ELSE "Another comment" END AS comment
FROM
table;
In pandas:
table
.assign(comment = table['column_1']
.apply(lambda column_1: 'Comment' if column_1 > 10 else ('Other comment' if column_1 < 1 else 'Another comment')))
[['column_1', 'comment']]