【问题标题】:Convert for loop output tuple into dataframe python将for循环输出元组转换为数据框python
【发布时间】:2019-05-25 21:31:52
【问题描述】:

大家好,我正在 Knime 中执行一个 Python 代码,该代码位于本网站 here! ,使用 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

所以我修改了 2 次失败尝试的代码,如下所示:

尝试: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 数据帧来执行节点(最小的处理单元)。

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

谢谢

【问题讨论】:

  • 是的,KNIME 要求 output_table 是 Pandas DataFrame。那么您是否尝试过创建一个?如果您需要帮助,请参阅 the docs
  • 谢谢@nekomatic 我会看看那个,但我认为最后三行代码都在尝试创建 Pandas DataFrame。如果有什么遗漏,请告诉我。

标签: python loops dataframe tuples knime


【解决方案1】:

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

所以删除或调整 if 语句将解决问题

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多