如何访问玛瑙公式行索引?
问题描述:
使用Python的表格数据图书馆agate我想定义一个计算Formula
,它访问行索引。我试图如何访问玛瑙公式行索引?
agate.Formula(agate.Text(), lambda r: r.index())
但这不起作用,因为对象不提供(行)指数(不像列对象!)。是否有访问行索引内公式的方法吗?
(我需要这一点是为了创造具有独特的每一行值的新列。)
答
从我的研究中我得出结论,那就是无法访问标准Formula
功能中的行号。 (当然,我很高兴被证明是错误的!)
但是为了达到什么问我可以继承Formula
的问题,改变调用函数的签名添加行号作为参数:
class EnumeratedFormula(agate.Formula):
"""
An agate formula which provides a row index to its compute function
The function used has now the signature f(i,r)
"""
def run(self, table):
new_column = []
for i, row in enumerate(table.rows):
v = self._func(i,row)
if self._cast:
v = self._data_type.cast(v)
new_column.append(v)
return new_column
有了这个我可以写这产生具有独特的每一行唯一值的新列的计算表达式:
EnumeratedFormula(agate.Text(), lambda i, r: str(i)))
答
这是从功能__doc__
:
必须为指定的数据类型返回一个有效的值。 :PARAM投:如果:代码:True
,每个返回值将被转换为指定的\ N:代码:data_type
,以确保它是有效的。
这是从offitial教程:
number_type = agate.Number()
def five_year_total(row):
columns = ('2009', '2010', '2011', '2012', '2013')
return sum(tuple(row[c] for c in columns)]
formula = agate.Formula(number_type, five_year_total)
new_table = table.compute([
('five_year_total', formula)
])
这两个判断,我要说的是,你的数据类型是错误的,index()
函数返回一个对象类型int
你是text()
。 尝试使用从码头agate.Number()
之一。 我使用的教程是http://agate.readthedocs.io/en/1.6.0/cookbook/excel.html#simple-formulas
的式(输出)的数据类型是*不*的问题。正如问题中提到的,我的代码行无效,因为'r'没有行索引,但这正是我的问题:如何访问公式中的行索引*?你的回答根本没有解决这个问题。 – halloleo
我会更新的答案。在此期间,我开始使用图书馆。 –