按hier分组修正val列负值:用前一行/前调整值的1/2替换
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:
| hier | val |
|---|---|
| A | 100 |
| A | -50 |
| A | -20 |
| B | 80 |
| B | -10 |
After running either solution, the adjusted_val column will look like this:
| hier | val | adjusted_val |
|---|---|---|
| A | 100 | 100 |
| A | -50 | 50 |
| A | -20 | 25 |
| B | 80 | 80 |
| B | -10 | 40 |
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

