如何对Pandas DataFrame的IMPACT列求和并添加总计行(排除NA)
需求与解决方案
需求
对DataFrame中的IMPACT列进行求和,在数据底部添加一行名为Total的行,填入求和后的整数值,求和时需排除NA和N/A值。
现有代码
import pandas as pd import openpyxl import numpy as np pd.set_option('display.max_colwidth', None) file = 'sheet.xlsx' planilha = pd.read_excel(file,header=None,names=['Description','IMPACT']) def my_function(text): key_string = 'IMPACT:' if '[' and ']' in text: my_slice = text[text.find(key_string)+len(key_string):text.find(']')] else: my_slice = text[text.find(key_string)+len(key_string):] return my_slice planilha['IMPACT'] = planilha['Description'].apply(lambda x: my_function(x))
解决方案步骤
- 清洗
IMPACT列数据:将列中的NA、N/A标记为缺失值(NaN),并将列转换为数值类型,方便后续求和计算。 - 计算有效总和:跳过所有缺失值,对
IMPACT列的有效数值求和,最终转为整数。 - 添加合计行:构造包含
Total标识的行数据,合并到原DataFrame底部。
完整代码
import pandas as pd import openpyxl import numpy as np pd.set_option('display.max_colwidth', None) file = 'sheet.xlsx' planilha = pd.read_excel(file, header=None, names=['Description', 'IMPACT']) def my_function(text): key_string = 'IMPACT:' if '[' in text and ']' in text: my_slice = text[text.find(key_string)+len(key_string):text.find(']')] else: my_slice = text[text.find(key_string)+len(key_string):] return my_slice # 从Description中提取IMPACT值 planilha['IMPACT'] = planilha['Description'].apply(lambda x: my_function(x)) # 清洗数据:将NA/N/A转为NaN,同时强制转换为数值类型 planilha['IMPACT'] = pd.to_numeric(planilha['IMPACT'], errors='coerce') # 计算总和,自动跳过NaN值 total_impact = int(planilha['IMPACT'].sum(skipna=True)) # 构造Total行 total_row = pd.DataFrame({'Description': ['Total'], 'IMPACT': [total_impact]}) # 合并原数据与Total行 planilha = pd.concat([planilha, total_row], ignore_index=True) # 输出结果 print(planilha)
代码说明
pd.to_numeric(..., errors='coerce'):把无法转换为数值的内容(如NA、N/A)统一转为NaN,确保列是可计算的数值类型。sum(skipna=True):默认跳过NaN值计算总和,最后用int()转换为整数符合需求。pd.concat:将合计行与原数据合并,ignore_index=True重置索引避免出现重复索引问题。
内容的提问来源于stack exchange,提问作者Trombeta
相关产品推荐
相关产品推荐

