2

我正在尝试选择表中的行并使用 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按原样使用选择功能来填充。etl.select如果我替换post_code为看起来像,该呼叫将起作用

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 文档中的所有内容,但似乎无法弄清楚。

任何帮助深表感谢。

4

1 回答 1

2

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

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

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

在控制台中测试这个

>>> "{{Postcode}} == {post_code}".format(post_code=1234)
'{Postcode} == 1234'
于 2018-09-20T13:23:38.047 回答