如何在DataFrame中仅对最后两行运算生成FI及FI/VA行
问题描述
现有如下结构化数据集:
Industry Country Year AUS AUS AUT AUT ... A AUS 1 0.5 0.2 0.1 0.01 B AUS 2 0.3 0.5 2 0.1 A AUT 3 1 1.2 1.3 0.3 B AUT 4 0.5 0 0.8 2 ... ... ... ... ... ... .... VA 11 10 47 55 tot 24 23 50 70
需要仅针对最后两行(VA和tot行)进行运算,最终得到以下结果:
Industry Country Year AUS AUS AUT AUT ... A AUS 1 0.5 0.2 0.1 0.01 B AUS 2 0.3 0.5 2 0.1 A AUT 3 1 1.2 1.3 0.3 B AUT 4 0.5 0 0.8 2 ... ... ... ... ... ... .... VA 11 10 47 55 FI 13 13 3 15 FI/VA 1.2 1.3 0.06 0.27
其中:
FI为tot与VA对应列的差值FI/VA为FI与VA对应列的商(结果保留两位小数)
解决方案(Python pandas实现)
假设数据已读取为pandas的DataFrame对象df,按以下步骤操作:
提取目标行
直接通过索引定位最后两行(确认VA是倒数第二行,tot是最后一行):va_row = df.iloc[-2] tot_row = df.iloc[-1]也可通过
Industry列的值精准匹配:va_row = df[df['Industry'] == 'VA'].iloc[0] tot_row = df[df['Industry'] == 'tot'].iloc[0]计算FI行数据
复制VA行的结构,替换标识并执行减法:fi_row = va_row.copy() fi_row['Industry'] = 'FI' # 定位所有数值列(从第4列开始,对应示例中的AUS、AUT等列) numeric_cols = df.columns[3:] fi_row[numeric_cols] = tot_row[numeric_cols] - va_row[numeric_cols]计算FI/VA行数据
同样复制结构,执行除法并保留两位小数:fi_va_row = va_row.copy() fi_va_row['Industry'] = 'FI/VA' fi_va_row[numeric_cols] = (fi_row[numeric_cols] / va_row[numeric_cols]).round(2)更新数据集
删除原tot行,添加新计算的两行:# 移除tot行 df = df[df['Industry'] != 'tot'] # 追加FI和FI/VA行 df = pd.concat([df, pd.DataFrame([fi_row, fi_va_row])], ignore_index=True)
执行完成后,df即为所需的结果数据集。
内容的提问来源于stack exchange,提问作者Maximilian
相关产品推荐
相关产品推荐

