Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
gygabyte017 opened this issue Mar 7, 2021 · 1 comment
Closed

Comments

@gygabyte017
Copy link

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

@kesmit13
Copy link
Contributor

kesmit13 commented Mar 8, 2021

If it was just 0 or 1, I think you could use just the Python methods to do this since the boolean result would get mapped to an integer, but I think the addition of a third branch might mean having to use some sort of SAS-specific functions. I can't say that I'm coming up with any ideas that wouldn't require something along the lines of what you have in your example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants