0

I would like to change values in a dataframe using np.select However, I'm getting an error and google didn't find any solution for similar issues. Could somebody help me out? Thank you in advance for your time and help. Here is my dataframe

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[1,0,-0.6,-1,0.7],
       'B':[-1,1,-0.3,0.5,1]})
df

Then, this my code where df values are recoded as follow:

  • values less than or equal to -0.5 become -1

  • values greater than -0.5 and less than or equal to 0.5 become 0

  • values greater than 0.5 become 1

    new_df = pd.DataFrame( np.select([df.le(-0.5), df.gt(-.5) & df.le(0.5), df.gt(0.5)], [-1, 0, 1]), index=df.index, columns=df.columns )

    new_df

desired output

My code gave me the following error and I'm not sure what's wrong and how to fix it KeyError: <function dispatch_to_series..column_op at 0x7f64a469d158> my full error

Amilovsky
  • 397
  • 6
  • 15

1 Answers1

0

You could try this instead - I believe rounding the decimals to zero digits obeys all your conditions as well :

# default decimals is 0 
df_new = df.round()

# or this if you need more control on each column decimal places
df_new = df.round({'A': 0, 'B': 0})
  • Yes, df.round() works for this particular problem. However, I'm still puzzled about why I'm getting that error. Anyway, thank you for your time. – Amilovsky Apr 07 '22 at 20:20