简体   繁体   English

如何根据 python 中的条件将一行中的值替换为上一行?

[英]How to replace a value in a row with the previous row based on a condition in python?

I have a data table:我有一个数据表:

Index Value

0      NaN

1      1.15

2      2.25

3      2.33

Condition: First check wherever previous row value is not NaN then replace current row value with previous row value.条件:首先检查前一行值不是 NaN 的位置,然后将当前行值替换为前一行值。

Desired output:所需的 output:

Index Value

0      NaN

1      1.15

2      1.15

3      1.15

Compare values for missing values, then get first consecutive value and replace another by DataFrame.where , forward filling missing values and last replace original missing values:比较缺失值的值,然后获取第一个连续值并用DataFrame.where替换另一个值,向前填充缺失值并最后替换原始缺失值:

df = pd.DataFrame({'Value':[np.nan,1.15,2.15,3.15,np.nan,2.1,2.2,2.3]})

m = df.notna()
df1 = df.where(m.ne(m.shift())).ffill().where(m)

print (df1)
   Value
0    NaN
1   1.15
2   1.15
3   1.15
4    NaN
5   2.10
6   2.10
7   2.10

Details :详情

print (m.ne(m.shift()))
  Value
0   True
1   True
2  False
3  False
4   True
5   True
6  False
7  False

print (df.where(m.ne(m.shift())))
 Value
0    NaN
1   1.15
2    NaN
3    NaN
4    NaN
5   2.10
6    NaN
7    NaN

print (df.where(m.ne(m.shift())).ffill())
   Value
0    NaN
1   1.15
2   1.15
3   1.15
4   1.15
5   2.10
6   2.10
7   2.10

暂无
暂无

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

相关问题 根据条件从当前行和上一行中的值创建列表 - Create list from value in current row and previous row based on condition 如何根据 pandas DataFrame 中的条件从当前行值中减去前一行值? - how to subtract previous row value from current row value based on condition in pandas DataFrame? 如果满足条件,如何用前一行替换 pandas 列行 - How to replace a pandas column row with the previous row if a condition is met 使用 pandas 根据条件分组中的上个月最后一个值,将所有空值替换为最后一行 - Using pandas replace all empty values with last row based on previous month last value in a group by condition Pandas:如果满足条件,则将列的值替换为前一行的值 - Pandas: Replace value of column with previous row value if condition is met Python - 如何比较行和前一行的值并根据条件返回时间差? - Python - How to compare the values for row and previous row and return time difference based on condition? 如何根据数据框中的条件将行与前一行组合 - How to combine row with previous row based on condition in dataframe 如何根据先前的行和列条件填充 pandas dataframe 的行? - How to populate row of pandas dataframe based on previous row and column condition? Python:如何迭代行并根据前一行计算值 - Python: How to iterate over rows and calculate value based on previous row 根据条件将字符串值替换为前一行值 - Pandas - Replace string value with previous row value based on conditionals - Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM