0

I am importing both pandas and numpy in Jupyter notebooks

I have 2 columns x and y in dataframe (df) which are fed in from a larger CSV but these are the 2 columns that are relevant to the calculation, x is an int, y is a float.

In SAS I would type:

case
when t1.x <> 1 or t1.y not in (1,2)
then z
else t1.y
end

I can't get that to work in Python whereby the column y is overwritten when calculating the formula I've been using conditions and choices for the simpler queries but the following doesn't work:

conditions = [
    (df['x'] != 1)] | (df['y'] not in (1,2))]

choices = [z]

df['y'] = np.select(conditions, choices, default=(df['y']))

Any suggestions?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
AndrewK
  • 27
  • 6
  • Are you using `<>` as meaning not equal? SAS also uses that symbol as meaning the binary MAX operator in some contexts. – Tom Apr 16 '20 at 12:07
  • Change `(df['y'] not in (1,2))` to `~(df['y'].isin([1,2]))` – jezrael Apr 16 '20 at 12:08
  • Your description only talks about two variables X and Y, but your code references a third variable Z. – Tom Apr 16 '20 at 12:10
  • @Tom - to mean not in, apologies for not being clear The z is referring to be the generic version of the "." in SAS. – AndrewK Apr 16 '20 at 12:11
  • @jezrael This question is different than the question you linked. That question is just how to subset. This question is essentially how do if/then logic to select either Y or Z values. – Tom Apr 16 '20 at 12:34
  • @Tom - Solution working if change `isin` and then change `choices = [z]` to `choices = [df.z]` – jezrael Apr 16 '20 at 12:36
  • @jezrael There is no reference to `choices` in the answer to the question you linked. Is there a better question to link to instead? If not then just post an answer to this question. – Tom Apr 16 '20 at 12:56
  • @Tom - I dont know if post or not, then obviously create comment solution. Here is possible use `df['y'] = np.were((df['x'] != 1) | ~(df['y'].isin([1,2])), df.z, df.y)` if 2 conditions only – jezrael Apr 16 '20 at 13:03
  • 1
    @jezrael Thank you for that last answer - works a treat. What would happen if I had more than 2 conditions? – AndrewK Apr 16 '20 at 14:35

0 Answers0