如何修改表格Value列:仅保留各索引组最新条目为True
需求与解决方案
原始表格
| Index | Another header | Value |
|---|---|---|
| index1 | a | True |
| a | True | |
| a | True | |
| b | True | |
| index2 | c | True |
| index2 | c | True |
| index2 | c | True |
表格数据按日期从最早到最新排序,需实现以下规则:
- 按
Index分组,再在每个Index组内按Another header二次分组 - 每个
Another header子组中,仅保留**最后一条(最新)**数据的Value为True,其余改为False - 若某个
Another header子组仅含1条数据,直接将其Value改为False
目标表格
| Index | Another header | Value |
|---|---|---|
| index1 | a | False |
| a | False | |
| a | True | |
| b | False | |
| index2 | c | False |
| c | False | |
| c | True |
方案1:Excel实现
- 补全Index空值:选中
Index列,按Ctrl+G打开定位窗口,选择「空值」,输入=A2(假设表头在第一行,数据从第二行开始,A2为上一行的Index值),按Ctrl+Enter批量填充。 - 添加分组标识列:新增D列命名为
分组标识,输入公式=A2&B2,下拉填充,合并Index和Another header作为分组依据。 - 添加组内行号列:新增E列命名为
组内行号,输入公式=COUNTIF($D$2:D2,D2),下拉填充,标记每个分组内的行序号(从1递增)。 - 添加组内总行数列:新增F列命名为
组内总行数,输入公式=COUNTIF($D:$D,D2),下拉填充,获取每个分组的总行数。 - 更新Value列:选中C2单元格,输入公式
=IF(E2=F2,IF(F2>1,TRUE,FALSE),FALSE),下拉填充完成批量修改。 - (可选)将Value列的公式粘贴为值后,删除辅助列。
方案2:Python Pandas实现
假设数据已读取为DataFrame,代码如下:
import pandas as pd # 示例数据(实际替换为你的数据源读取逻辑) df = pd.DataFrame({ 'Index': ['index1', '', '', '', 'index2', 'index2', 'index2'], 'Another header': ['a', 'a', 'a', 'b', 'c', 'c', 'c'], 'Value': [True]*7 }) # 补全Index列的空值 df['Index'] = df['Index'].ffill() # 标记每个(Index, Another header)分组的最后一行 df['is_last'] = df.groupby(['Index', 'Another header']).cumcount(ascending=False) == 0 # 根据规则更新Value列 def update_value(row): group_size = df[(df['Index'] == row['Index']) & (df['Another header'] == row['Another header'])].shape[0] return row['is_last'] if group_size > 1 else False df['Value'] = df.apply(update_value, axis=1) # 可选:恢复Index列的空值格式(与原始表格一致) df['Index'] = df['Index'].where(df['Index'] != df['Index'].shift(), '') print(df)
内容的提问来源于stack exchange,提问作者encrypted-ninja
相关产品推荐
相关产品推荐

