You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按hier分组修正val列负值:用前一行/前调整值的1/2替换

Fix Negative Values in val Column (Grouped by hier)

Alright, let's figure out how to fix those negative values in your val column exactly as you described—grouping by hier and replacing negatives with half the previous adjusted value, even when they're consecutive. Here are solutions for the two most common tools used for this kind of data wrangling:

R Solution (dplyr + purrr)

We'll use group_by() to split the data by hier, then purrr::accumulate() to iterate through each group's val column and adjust values on the fly. This function is perfect here because it carries over the last adjusted value to handle consecutive negatives automatically.

library(dplyr)
library(purrr)

# Replace `your_data` with your actual dataframe name
adjusted_data <- your_data %>%
  group_by(hier) %>%
  mutate(adjusted_val = accumulate(val, function(prev_val, curr_val) {
    # If current value is negative, use half the previous adjusted value
    if (curr_val < 0) {
      prev_val / 2
    } else {
      # Keep the current value if it's non-negative
      curr_val
    }
  })) %>%
  ungroup()

Python Solution (pandas + itertools)

In pandas, we'll group by hier and use itertools.accumulate() to process each group sequentially. This works the same way as the R solution—passing the last adjusted value to the next step to handle consecutive negatives.

import pandas as pd
from itertools import accumulate

def adjust_group_negatives(group):
    def adjust_single_val(prev_val, curr_val):
        return prev_val / 2 if curr_val < 0 else curr_val
    
    # Apply the adjustment to the group's val column
    group['adjusted_val'] = list(accumulate(group['val'], adjust_single_val))
    return group

# Replace `your_data` with your actual dataframe name
adjusted_data = your_data.groupby('hier').apply(adjust_group_negatives).reset_index(drop=True)

Example to See It in Action

Let's use a small sample dataset to verify:

hierval
A100
A-50
A-20
B80
B-10

After running either solution, the adjusted_val column will look like this:

hiervaladjusted_val
A100100
A-5050
A-2025
B8080
B-1040

Notice how consecutive negatives in group A use the already adjusted value from the prior row—exactly what you asked for!

内容的提问来源于stack exchange,提问作者Selcuk Akbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:16:42