【问题标题】:Writing prediction results into separate files for each group using 'for loop' in Python在 Python 中使用“for loop”将预测结果写入每个组的单独文件中
【发布时间】:2019-06-21 16:00:51
【问题描述】:

我有一个数据框“c”,它有一个名为“UNITID”的属性。我已经根据不同的“UNITID”划分了数据框,并在每个“UNITID”上运行了神经网络模型。请参见下面的代码。我使用 enumerate 函数将它们标记为 c1,c2,...cn 并存储在 'c_new' 中

c_count = c['UNITID'].nunique()
c_new={"c{0}".format(i+1):j[1]for i,j in enumerate(c.groupby('UNITID'))}
for i in range(c_count):
    i = i+1
    c_data = 'c'+str(i)
    print("==============================-------{}-------===========================".format(i))
    c_new[c_data] = c_new[c_data].set_index('DATETIME')
    values = c_new[c_data].values
    # Encoding categorical data
    ..
    #Convert Categories in Text into numbers using Label encoder/ OneHotEncoding
    ..
    # split into train and test sets
    ..
    # reshape input to be 3D [samples, timesteps, features]
    ..
    #Scale and Normalize inputs
    ..
    # Deep Neural Network model
    ..
    # fit network
    ..
    # make a prediction
    ..

    #performance metrics: MAE, MSE, RMSE, Rsq
    ... 

每次为每个 UNITID 运行模型时,都会生成新的预测结果,但我当前的代码仅将结果覆盖到具有相同文件名的同一个文件中(有意义,因为 df.to_csv 就是这样作品)。

我想要的是每次生成新结果时将结果写入单独的文件。对于每个 c{i},其中 i = 1,2.. n。 ;每个的预测输出文件应该是 c_out_{i},如下所示。

i/p file --> o/p

c1 --> c_out_1
c2 --> c_out_2
c3 --> c_out_3
.
.
cn --> c_out_n

我怎样才能做到这一点?

#Write  predictions to file
test_y = pd.DataFrame(test_y) #Actual values
yhat = pd.DataFrame(yhat) #predicted values using the model

test_y.rename(columns= {0: 'Actual value'}, inplace = True)
yhat.rename(columns = {0: 'Pred value'}, inplace = True)

new = pd.concat([test_y, yhat], axis = 1)
#print(('ct'+ str(i)))
new.to_csv('c_out_{i}.csv') #I want to write a different output csv file for each UNITD's prediction; 

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 文件名 = "c_out_" + str(i) + ".csv"
  • 你也可以试试new.to_csv('c_out_%s.csv' %i)
  • 谢谢@Nightmerker,它有效!
  • 谢谢@Bazingaa,它有效!
  • @shweta24:不客气 :)

标签: python pandas csv for-loop


【解决方案1】:

在你的 for 循环中添加:

new.to_csv('c_out_' + str(i) + '.csv')

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多