将for循环输出元组转换为数据框python

时间:2019-05-25 21:31:52

标签: python loops dataframe tuples knime

大家好,我在Knime中执行的是在该网站here中找到的python代码! ,使用Knime-Python扩展,但我需要将最佳的3个模型配置导出到数据帧中,该数据帧由for循环生成并表示为元组。

代码的原始最后一位是

if __name__ == '__main__':
    # load dataset
    series = read_csv('daily-total-female-births.csv', header=0, index_col=0)
    data = series.values
    print(data.shape)
    # data split
    n_test = 165
    # model configs
    cfg_list = sarima_configs()
    # grid search
    scores = grid_search(data, cfg_list, n_test)
    print('done')
    # list top 3 configs
    for cfg, error in scores[:3]:
        print(cfg, error)

并且应该返回

done
[(0, 1, 2), (2, 0, 2, 0), 't'] 54.767582003072874
[(0, 1, 1), (2, 0, 2, 0), 'ct'] 58.69987083057107
[(1, 1, 2), (0, 0, 1, 0), 't'] 58.709089340600094

因此,我通过两次失败的尝试修改了代码,如下所示:

尝试:1

if __name__ == '__main__':
    # load dataset
    series = read_csv('C:\\Users\\Downloads\\shampoo.txt', header=0, index_col=0, date_parser=custom_parser)
    data = series.values
    print(data.shape)
    # data split
    n_test = 12
    # model configs
    cfg_list = sarima_configs()
    # grid search
    scores = grid_search(data, cfg_list, n_test)
    print('done')
    # list top 3 configs
    for cfg, error in scores[:3]:
        df=pd.DataFrame(cfg, error)
        output_table = df

尝试:2

if __name__ == '__main__':
    # load dataset
    series = read_csv('C:\\Users\\Downloads\\shampoo.txt', header=0, index_col=0, date_parser=custom_parser)
    data = series.values
    print(data.shape)
    # data split
    n_test = 12
    # model configs
    cfg_list = sarima_configs()
    # grid search
    scores = grid_search(data, cfg_list, n_test)
    print('done')
    # list top 3 configs
    for cfg, error in scores[:3]:
        df.append({'cfg': cfg, 'error': error},ignore_index=True)
    output_table = df

问题在于,Knime需要定义一个输出表(例如pandas数据帧)以执行该节点(最小的处理单元)。

我希望像下面的图像(https://ibb.co/xCGqVtx)一样定义output_table

谢谢

1 个答案:

答案 0 :(得分:1)

问题在于您的主要代码的结构类似于命令行python脚本,即它期望__name__ == '__main__'。实际上,情况并非如此。您可以尝试在print(__name__)结构之外添加if语句。对于Python Script节点,我得到builtins

因此,删除或调整if语句将解决问题