将数字上限/阈值应用于pandas数据帧

时间:2018-02-13 14:37:41

标签: pandas numpy dataframe lambda apply

从第1天到第7天,我有一个三人(John,Terry,Henry)的数据框。

        1     2     3     4     5     6      7
John    1.3   2.8   3.0   4.4   2.6   3.1    4.8
Terry   1.1   2.3   4.1   5.5   3.7   2.1    3.8
Henry   0.3   1.0   2.0   3.0   2.7   1.1    2.8

如何设置分数上限,以便一旦分数达到> 2.5,无论分数是什么

,从那天起的所有分数都设置为3

输出应为:

        1     2     3     4     5     6      7
John    1.3   3.0   3.0   3.0   3.0   3.0    3.0
Terry   1.1   2.3   3.0   3.0   3.0   3.0    3.0
Henry   0.3   1.0   2.0   3.0   3.0   3.0    3.0

我尝试应用首先定义一个函数并使用np.apply(threshold_1,axis = 1)但它没有工作:

def threshold_1(x):
    if (x > 2.5 & x+1 < 2.5):
        return 3
    if (x > 2.5 & x+1 > 2.5):
        return 3
    else:
        return x

2 个答案:

答案 0 :(得分:2)

使用:

df = df.mask(df.gt(2.5).cumsum(1).gt(0), 3)
#same as
#df = df.mask((df > 2.5).cumsum(axis=1) > 0, 3)
print (df)
         1    2    3    4    5    6    7
John   1.3  3.0  3.0  3.0  3.0  3.0  3.0
Terry  1.1  2.3  3.0  3.0  3.0  3.0  3.0
Henry  0.3  1.0  2.0  3.0  3.0  3.0  3.0

<强>详细

首先按2.5gt比较所有值:

print (df.gt(2.5))
           1      2      3     4     5      6     7
John   False   True   True  True  True   True  True
Terry  False  False   True  True  True  False  True
Henry  False  False  False  True  True  False  True

然后按axis=1

按列获取cumsum
print (df.gt(2.5).cumsum(axis=1))
       1  2  3  4  5  6  7
John   0  1  2  3  4  5  6
Terry  0  0  1  2  3  3  4
Henry  0  0  0  1  2  2  3

eq0进行比较:

print (df.gt(2.5).cumsum(axis=1).gt(0))
           1      2      3     4     5     6     7
John   False   True   True  True  True  True  True
Terry  False  False   True  True  True  True  True
Henry  False  False  False  True  True  True  True

最后由mask True之后的3替换print (df.mask(df.gt(2.5).cumsum(1).gt(0), 3)) 1 2 3 4 5 6 7 John 1.3 3.0 3.0 3.0 3.0 3.0 3.0 Terry 1.1 2.3 3.0 3.0 3.0 3.0 3.0 Henry 0.3 1.0 2.0 3.0 3.0 3.0 3.0

numpy

为了提高性能,可以使用a = df.values df1 = pd.DataFrame(np.where(np.cumsum(a > 2.5, axis=1) > 0, 3, a), index=df.index, columns=df.columns) print (df1) 1 2 3 4 5 6 7 John 1.3 3.0 3.0 3.0 3.0 3.0 3.0 Terry 1.1 2.3 3.0 3.0 3.0 3.0 3.0 Henry 0.3 1.0 2.0 3.0 3.0 3.0 3.0

<form name="signin" class="js-form-submit needs-validation" action="/signin">
  <div class="form-group">
    <label for="username">User Name</label>
    <input class="form-control" id="username" name="username" autofocus>
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password" >
  </div>
  <button type="submit" class="btn btn-primary mb-2">Submit/button>
</form>

答案 1 :(得分:0)

我们可以使用idxmax

s=df.gt(2.5).idxmax(1)
for x in list(range(len(s))):
    df.loc[s.index[x],s[x]:]=3

df
Out[585]: 
         1    2    3    4    5    6    7
John   1.3  3.0  3.0  3.0  3.0  3.0  3.0
Terry  1.1  2.3  3.0  3.0  3.0  3.0  3.0
Henry  0.3  1.0  2.0  3.0  3.0  3.0  3.0