0

我有下表:

+----------------+---------+------------+
| Cambridge Data | IRR     | Price List |
+================+=========+============+
| '3/31/1989'    | '4.37%' |            |
+----------------+---------+------------+
| '4/30/1989'    | '5.35%' |            |
+----------------+---------+------------+

我想转换表格并填充100剑桥数据中日期为“1989 年 4 月 30 日”的价目表。我使用petl具有以下功能:

# Add an initial price to base calculations for Price List
def insert_initial_price(self, table):
    table = etl.convert(table, 'Price List', lambda v, row: v = '100' if row['Cambridge Parser'] == '3/31/1989', pass_row=True)
    return table

这是一个使用 petl 文档中类似方法的示例:

>>> # conversion can access other values from the same row
... table12 = etl.convert(table1, 'baz',
...                       lambda v, row: v * float(row.bar),
...                       pass_row=True)
>>> table12
+-----+-------+--------------------+
| foo | bar   | baz                |
+=====+=======+====================+
| 'A' | '2.4' | 28.799999999999997 |
+-----+-------+--------------------+
| 'B' | '5.7' |              193.8 |
+-----+-------+--------------------+
| 'C' | '1.2' |               67.2 |
+-----+-------+--------------------+
4

1 回答 1

1

您的功能存在三个主要问题。

首先,您尝试为v. 但是赋值是语句,而不是表达式。您不能将语句放在 Python 中的表达式中,并且lambda是一个表达式。但是你总是可以使用def

def func(v, row):
    v = '100' if row['Cambridge Parser'] == '3/31/1989'
table = etl.convert(table, 'Price List', func, pass_row=True)

其次,'100' if row['Cambridge Parser'] == '3/31/1989'不是 Python 中的有效表达式。if语句可能不需要else,但if表达式需要。因此,它必须看起来更像这样:

def func(v, row):
    v = '100' if row['Cambridge Parser'] == '3/31/1989' else v
table = etl.convert(table, 'Price List', func, pass_row=True)

… 或者:

def func(v, row):
    if row['Cambridge Parser'] == '3/31/1989':
        v = '100'
table = etl.convert(table, 'Price List', func, pass_row=True)

最后,即使您解决了这个问题,分配一个值v也不会有任何好处。v只是函数的参数名称。将该名称重新绑定到其他值是没有意义的;退出函数后,该参数将不再存在。特别是,它不会对传递给函数的任何值产生任何影响。

如果您查看示例函数,它不会尝试分配任何内容,它只是返回新值。这就是你想在这里做的。所以,要么:

def func(v, row):
    if row['Cambridge Parser'] == '3/31/1989':
        return '100'
    else:
        return v
table = etl.convert(table, 'Price List', func, pass_row=True)

…或者,如果你想让它尽可能简洁,即使这意味着你不理解自己的代码:

table = etl.convert(table, 'Price List', lambda v, row: '100' if row['Cambridge Parser'] == '3/31/1989' else v, pass_row=True)
于 2018-06-06T20:58:03.680 回答