【问题标题】:ETL table selection by Variable通过变量选择 ETL 表
【发布时间】:2019-02-24 19:13:46
【问题描述】:

我正在尝试选择表中的行并使用 PETL 使用原始表中的信息创建一个新表。

我现在的代码是:

import petl as etl


table_all = (
    etl.fromcsv("practice_locations.csv")
        .convert('Practice_Name', 'upper')
        .convert('Suburb', str)
        .convert('State', str)
        .convert('Postcode', int)
        .convert('Lat', str)
        .convert('Long', str)
)


def selection(post_code):
    table_selected = etl.select(table_all, "{Postcode} == 'post_code'")
    print(post_code)
    etl.tojson(table_selected, 'location.json', sort_keys=True)

但我似乎无法按原样使用选择功能来填充table_selected。如果我将post_code 替换为看起来像,etl.select 调用将起作用

table_selected = etl.select(table_all, "{Postcode} == 4510")

哪个输出正确的表显示为:

    +--------------------------------+--------------+-------+----------+--------------+--------------+
    | Practice_Name                  | Suburb       | State | Postcode | Lat          | Long         |
    +================================+==============+=======+==========+==============+==============+
    | 'CABOOLTURE COMBINED PRACTICE' | 'Caboolture' | 'QLD' |     4510 | '-27.085007' | '152.951707' |
    +--------------------------------+--------------+-------+----------+--------------+--------------+

我确定我只是想以一种错误的方式调用post_code,但我已经尝试了 PETL 文档中的所有内容,但似乎无法弄清楚。

非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x etl petl


    【解决方案1】:

    "{Postcode} == 'post_code'" 不会将 post_code 替换为传递给您的 selection 函数的值。

    您需要格式化您的选择字符串(并在使用format 时转义{Postcode})

    table_selected = etl.select(table_all, "{{Postcode}} == {post_code}".format(post_code=post_code))
    

    在控制台中测试这个

    >>> "{{Postcode}} == {post_code}".format(post_code=1234)
    '{Postcode} == 1234'
    

    【讨论】:

    • 如此接近!我之前有非常相似,但忘记在邮政编码周围添加第二组大括号,非常感谢,非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多