首页 > 解决方案 > 将文件名的标题添加到csv

问题描述

所以我遍历多个 csv 文件并使用 FBProphet 来获取它们的预测。然后,我使用 .to_csv 将所有预测写入一个 csv 文件。但是,我想获取文件名以在 csv 上将它们分开,并且不确定在使用 .to_csv 时是否有办法做到这一点。

filenames=['example1.csv','example2.csv','example3.csv']
for f in filenames:
    df=pd.read_csv(f)

    df.columns=['ds','y']
    df['ds']=pd.to_datetime(df['ds'])

    m=Prophet(seasonality_mode='multiplicative')
    m.fit(df)

    future=m.make_future_dataframe(periods=6,freq='M')

    forecast=m.predict(future)
    forecast[['ds','yhat','yhat_lower','yhat_upper']].tail()

    fig1=m.plot(forecast)
    fig2=m.plot_components(forecast)

    forecast.to_csv('final_data.csv',mode='a',header=True)

所以我得到的结果是

ds yhat yhat_lower yhat_upper                                    
example1 forecast

ds yhat yhat_lower yhat_upper                                   
example2 forecast

ds yhat yhat_lower yhat_upper                                    
example 3 forecast

我想得到的结果是

example 1 filename    
ds yhat yhat_lower yhat_upper                                   
example1 forecast

example 2 filename                                                    
ds yhat yhat_lower yhat_upper    
example2 forecast

example 3 filename   
ds yhat yhat_lower yhat_upper  
example 3 forecast

标签: pythonpandascsvfacebook-prophet

解决方案


推荐阅读