Take a minimum between a column value and a constant global value

I would like to create a new column for this data frame, where I calculate the minimum between the column value and some global value (in this example 7). so my df has columns sessionand note, and my desired output column minValue:

session     note     minValue
1       0.726841     0.726841
2       3.163402     3.163402  
3       2.844161     2.844161
4       NaN          NaN

I use the built-in Python method min:

df['minValue']=min(7, df['note'])

and I have this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
+6
source share
2 answers

Use np.minimum:

In [341]:
df['MinNote'] = np.minimum(1,df['note'])
df

Out[341]:
   session      note  minValue   MinNote
0        1  0.726841  0.726841  0.726841
1        2  3.163402  3.163402  1.000000
2        3  2.844161  2.844161  1.000000
3        4       NaN       NaN       NaN

Also mindoes not understand array mapping, hence your error

+9
source

pandas - Series.clip().

:

import pandas

df = pandas.DataFrame({'session': [1, 2, 3, 4],
                       'note': [0.726841, 3.163402, 2.844161, float('NaN')]})

df['minVaue'] = df['note'].clip(upper=1.)
df

:

       note  session   minVaue
0  0.726841        1  0.726841
1  3.163402        2  1.000000
2  2.844161        3  1.000000
3       NaN        4       NaN

numpy.minimum , .clip() :

  • : df['note'].clip(lower=0., upper=10.)
  • : df['note'].abs().clip(upper=1.).round()
+2

Source: https://habr.com/ru/post/1615716/


All Articles