处理表格(数字里有,代码不认为他是数字的情况)

表格在CSV2024_actual

需求,把每个月的cost相加,最后算出全年度cost,把每个Q的cost相加,q1+q2+q3+q4,得出q的总和

遇到问题,一开始算出来都是0,后面发现数字之间有千位分隔符,所以代码不认为他是数字,当他是object

处理方法:

1.读取表格 pandas

2.找到所有表头里有cost的那一列

3.月份里没有q,删除有q的列,并且把q1q2q3q4单独再找出来

4.表格的内容删除,并且让代码认为这些都是数字

5.最后相加,打印

import pandas as pd

# 加载 CSV 文件
file_path = r'E:/CSV2024_actual.csv'
csv_data = pd.read_csv(file_path)

# 识别并选取只代表单独月份的成本列
monthly_cost_columns = [col for col in csv_data.columns if 'cost' in col.lower() and 'q' not in col.lower()]

# 识别 Q1 和 Q2 成本列
q1_cost_columns = [col for col in csv_data.columns if 'cost' in col.lower() and 'q1' in col.lower()]
q2_cost_columns = [col for col in csv_data.columns if 'cost' in col.lower() and 'q2' in col.lower()]
q3_cost_columns = [col for col in csv_data.columns if 'cost' in col.lower() and 'q3' in col.lower()]
q4_cost_columns = [col for col in csv_data.columns if 'cost' in col.lower() and 'q4' in col.lower()]


# 转换成本列为数值类型
for col in monthly_cost_columns + q1_cost_columns + q2_cost_columns:
    csv_data[col] = csv_data[col].replace({',': ''}, regex=True)
    csv_data[col] = pd.to_numeric(csv_data[col], errors='coerce').fillna(0)

# 计算每个月的成本
monthly_costs = csv_data[monthly_cost_columns].sum()

# 计算 Q1 和 Q2 的总成本
q1_total_cost = csv_data[q1_cost_columns].sum().sum()
q2_total_cost = csv_data[q2_cost_columns].sum().sum()
q3_total_cost = csv_data[q2_cost_columns].sum().sum()
q4_total_cost = csv_data[q2_cost_columns].sum().sum()
Q_total = q1_total_cost+ q2_total_cost +q3_total_cost +q4_total_cost

# 打印每个月的成本和 Q1234的总成本
print("Monthly Costs:\n", monthly_costs)
print("Total Cost for Q:", Q_total)

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值