Post

统计剩余量

统计剩余量

统计某一列对应的数量列的总和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import pandas as pd


def read_excel_and_sum(file_path):
    # 读取 Excel 文件
    df = pd.read_excel(file_path, sheet_name='Sheet1')

    # 转换 '现有量' 列的数据类型为数值型
    df['现有量'] = pd.to_numeric(df['现有量'], errors='coerce')

    # 填充 NaN 值为0
    df['现有量'] = df['现有量'].fillna(0)

    # 创建字典用于存储 '物料规格' 列对应的 '现有量' 列值之和
    result_dict = {}

    # 遍历 DataFrame,统计 '现有量' 列值之和
    for index, row in df.iterrows():
        key = row['物料规格']
        value = row['现有量']
        result_dict[key] = result_dict.get(key, 0) + value

    # 打印结果,上下对齐
    for key, value in result_dict.items():
        print(f"{key:<25} 余量总数 {value:.1f}")


if __name__ == '__main__':
    file_path = '/tmp/bs.xlsx'
    read_excel_and_sum(file_path)
This post is licensed under CC BY 4.0 by the author.