Skip to content

Recommended way to create columns based on conditions in pandas flavor #112

Closed
@gygabyte017

Description

@gygabyte017

Hi, suppose I have a CASTable object with a string column col1. I want to create, using pandas flavor, a new column col2 such that for example

if col1 starts with 'A' => col2 = 0
else if col1 starts with 'B' => col2 = 1
else col2 = 2

I'm trying something like df["col2"] = df[df.col1.str.startswith('A')] ... ? but I'm not going far.
I saw that in pandas usually something like numpy.select is used but clearly numpy doesn't make sense here.

So what would you recommend here? I know I might use eval or a datastep but I would like to keep it as python as possible to improve debugging and standardization.

Just to set a context, in the application I'm writing I will need to apply to tables some long conditional rules coming from config files and calculate new columns, so I'd prefer to just write conditions with python syntax and apply them to CASTables letting swat doing the hard work (i.e. calculating all the computedvars), instead of writing the datastep as a string which would be harder to debug.

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions