pandas 数据框阈值-如果超过则保持数字固定 [英] Pandas dataframe threshold -- Keep number fixed if exceed

查看:58
本文介绍了 pandas 数据框阈值-如果超过则保持数字固定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从第1天到第7天,我有一个包含三个人(约翰,特里,亨利)的数据框.

I have a dataframe with scores of three persons (John, Terry, Henry) from day 1 to day 7.

          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,无论该得分是多少,从那天起所有得分都是固定的

How do I set a score ceiling such that once a score hits > 2.5, all scores from that day onwards is FIXED no matter what the score is

输出应为:

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

尝试以下操作无效.我首先对所有> 2.5到"1"的数字进行布尔运算,然后对累计和应用掩码:

Tried the following didn't work. I first do a boolean on all numbers > 2.5 to "1", then apply a mask to the cumulative sum:

df = df.mask((df > 2.5).cumsum(axis=1) > 0, df)

推荐答案

您可以通过

You can find first non NaN value by where with bfill and select first column by iloc:

m = (df > 2.5).cumsum(axis=1) > 0

s = df.where(m).bfill(axis=1).iloc[:, 0]
print (s)
John     2.8
Terry    4.1
Henry    3.0
Name: 1, dtype: float64

df = df.mask(m, s, axis=0)

shift 掩码并向前填充NaN到最后一个值:

m = (df > 2.5).cumsum(axis=1) > 0
df = df.mask(m.shift(axis=1).fillna(False)).ffill(axis=1)
print (df)
         1    2    3    4    5    6    7
John   1.3  2.8  2.8  2.8  2.8  2.8  2.8
Terry  1.1  2.3  4.1  4.1  4.1  4.1  4.1
Henry  0.3  1.0  2.0  3.0  3.0  3.0  3.0

这篇关于 pandas 数据框阈值-如果超过则保持数字固定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆