2

数学建模 Excel的批量写入与批量导出 - 月隐雲後

 1 year ago
source link: https://www.cnblogs.com/xiaohoulaoyue/p/17429197.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

数学建模 Excel的批量写入与批量导出

数学建模中编程手们常常会被要求将大量的数据进行批量的预测操作,并写入某个文件中

Excel的批量导出数据,用循环就可以简单实现,例如

import pandas as pd
for i in list(df['har_feacture']):
    result = df.loc[df['har_feacture'] == i]
    df_agg = result.groupby(['order_date'])['ord_qty'].mean().reset_index()

    # 从DataFrame对象df中读取需要的列并转换成DatetimeIndex对象
    df_agg['order_date'] = pd.to_datetime(df_agg['order_date'])

    df_agg = df_agg.set_index('order_date')

    # 对数据按月分组求和
    monthly_demand = df_agg['ord_qty'].resample('M').sum()
    
    s = pd.Series(monthly_demand)

    file_path = f"D:/data/f{i}.xlsx"
    
    #对s进行保存,保存在同一个文件夹中
    s.to_excel(file_path, index=True)

同时当我们对上述的每一个文件进行预测操作之后,需要将结果输出在一个.csv或.xlsx文件中,可以这样写:

import pandas as pd
import os

# 设置输入文件夹路径,这是存放所有文件的文件夹地址
input_folder_path = 'd:/data'
# 设置输出文件夹路径
output_folder_path = 'd:/data_csv'

# 获取文件夹中所有文件的列表
file_list = os.listdir(input_folder_path)

for file_name in file_list:
    # 判断文件是否为xls文件
    if file_name.endswith('.xlsx'):
        # 构造输入文件路径
        input_file_path = os.path.join(input_folder_path, file_name)
        # 读取xls文件
        df = pd.read_excel(input_file_path)
        # 构造输出文件路径
        output_file_path = os.path.join(output_folder_path, file_name.replace('.xlsx', '.csv'))
        # 将xls文件保存为csv文件
        df.to_csv(output_file_path, index=False)

值得注意的是,result.xlsx需要提前创建,否则会报错,我们也可以使用一个判断条件来自动创建,但是这里就不写了,自己在目标文件夹创建即可


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK