对于 petl 表,如何用零替换空值?
我会期待类似以下的内容:
tb_probii = etl.fromcsv("data.csv").fill("score", "", 0)
在这里寻找类似的功能:http: //petl.readthedocs.io/en/latest/_modules/petl/transform/fills.html
但没有运气:/
对于 petl 表,如何用零替换空值?
我会期待类似以下的内容:
tb_probii = etl.fromcsv("data.csv").fill("score", "", 0)
在这里寻找类似的功能:http: //petl.readthedocs.io/en/latest/_modules/petl/transform/fills.html
但没有运气:/
我不知道这是否是最好的方法。我真的很感谢你让petl
我注意到这个存在。
>>> import petl
>>> tb_probii = petl.fromcsv('trial.csv')
>>> tb_probii
+------+-------+
| team | score |
+======+=======+
| 'A' | '' |
+------+-------+
| 'B' | '25' |
+------+-------+
| 'C' | '35' |
+------+-------+
>>> from collections import OrderedDict
>>> mappings = OrderedDict()
>>> def f(s):
... if s == '':
... return '0'
... else:
... return s
...
>>> mappings['team'] = 'team'
>>> mappings['score'] = 'score', lambda s: f(s)
>>> tb_probii = petl.fieldmap(tb_probii, mappings)
>>> tb_probii
+-------+------+
| score | team |
+=======+======+
| '0' | 'A' |
+-------+------+
| '25' | 'B' |
+-------+------+
| '35' | 'C' |
+-------+------+
一些解释:
fieldmap
执行包含在OrderedDict
. 当我尝试这个时,我做了映射到一个新表。这就是为什么team
映射到自身。如果您保留同一张桌子,这可能是不必要的,尽管我对此表示怀疑。每个映射都是一个元组。forscore
表示score
要通过转换映射到自身。似乎有必要使用lambda
; 但是,lambda 不能包含if
语句。出于这个原因,我创建了f
lambda 调用的函数。我认为这些列是重新排序的,因为容器是 anOrderedDict
并且它是按列名按字典顺序排序的。也许它不必是一个OrderedDict
,但这是我在文档中找到的。
我向帮助组 python-etl@googlegroups.com 发送了电子邮件,创建者本人回复了一个完美运行的功能:
tb_probii = etl.fromcsv("data.csv").replace("score", "", 0)