简体   繁体   English

Pandas DataFrame 将连续值设置为 nan 直到列中的值发生变化

[英]Pandas DataFrame set consecutive values to nan until value in column changes

I have the following DataFrame, where Value refers to my observations, and Criterion indicates, when a Value should be set to np.nan .我有以下 DataFrame,其中Value是指我的观察结果, Criterion指示何时应将Value设置为np.nan

Value价值 Criterion标准
3 3 0 0
3 3 0 0
5 5 1 1
7 7 0 0
2 2 0 0
2 2 0 0
8 8 1 1
8 8 0 0
8 8 0 0
1 1 0 0

Whenever Criterion is equal to 1, I want to set the Value in the same row, as well as all consecutive Value s to zero until Value changes.每当Criterion等于 1 时,我想将同一行中的Value以及所有连续的Value设置为零,直到Value更改。 The desired output should look like this.所需的输出应如下所示。

Value价值 Criterion标准
3 3 0 0
3 3 0 0
nan 1 1
7 7 0 0
2 2 0 0
2 2 0 0
nan 1 1
nan 0 0
nan 0 0
1 1 0 0

Create groups by consecutive values in Value column and test if at least one 1 in Criterion , then set NaN per group in Series.mask :Value列中按连续值创建组并测试Criterion是否至少有一个1 ,然后在Series.mask每个组设置NaN

s = df['Value'].ne(df['Value'].shift()).cumsum()

df['Value'] = df['Value'].mask(df['Criterion'].groupby(s).transform('any'))
print (df)
   Value  Criterion
0    3.0          0
1    3.0          0
2    NaN          1
3    7.0          0
4    2.0          0
5    2.0          0
6    NaN          1
7    NaN          0
8    NaN          0
9    1.0          0

Or if need test first value is 1 per consecutive groups in column Criterion use:或者,如果需要测试第一个值是1Criterion每个连续组,请使用:

s= df['Value'].ne(df['Value'].shift()).cumsum()

df['Value'] = df['Value'].mask(df['Criterion'].groupby(s).transform('first').eq(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何基于另一列的NaN值设置熊猫数据框中的值? - How set values in pandas dataframe based on NaN values of another column? 切换列中的连续值直到条件改变 - Switch consecutive values in column until condition changes Pandas 基于另一个 dataframe 将多个列和行值设置为 nan - Pandas Set multiple column and row values to nan based on another dataframe pandas Dataframe基于键列,将NaN值替换为以前的值 - pandas Dataframe Replace NaN values with with previous value based on a key column 如果列名 == 年份且值为 NaN 熊猫,则将数据框中的值向左移动 - Shift values in dataframe to the left if column name == Year and value is NaN pandas 将 Pandas DataFrame 中的列值与“NaN”值连接起来 - Concatenate column values in Pandas DataFrame with “NaN” values 用列平均值替换 NaN 值不会改变 pandas dataframe NaN 值 - Replacing NaN values with column mean value does not change pandas dataframe NaN values 如何将熊猫数据帧系列中的连续重复值更改为 nan 或 0? - How to change consecutive repeating values in pandas dataframe series to nan or 0? 在熊猫数据框中移动一列会将数据设置为 NaN - shift a column in a pandas dataframe will set data to NaN 在 pandas dataframe 的列中将 NaN 值更改为 0 的问题 - Problem with changing NaN values to 0 in a column of a pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM