我正在尝试选择表格中的行,并使用 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 文档中的所有内容,但似乎无法弄清楚。
非常感谢任何帮助。
请您参考如下方法:
"{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'
