在列值和常量全局值之间取最小值

take minimum between column value and constant global value

我想为给定的数据框创建新列,我在其中计算列值和某个全局值之间的最小值(在本例中为 7)。所以我的 df 有 sessionnote 列,我想要的输出列是 minValue :

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

我正在使用内置的 Python 方法 min :

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

我有这个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

使用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

另外 min 不理解类似数组的比较,因此你的错误

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

会 return:

       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()