gpt4 book ai didi

python - petl - 如何用零替换空值

转载 作者:行者123 更新时间:2023-12-01 03:01:56 26 4
gpt4 key购买 nike

对于 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 映射到其自身的原因相同。如果您保留同一张 table ,这可能是不必要的,尽管我对此表示怀疑。每个映射都是一个元组。 score 表示 score 将通过转换映射到其自身。看来有必要使用lambda;但是,lambda 不能包含 if 语句。因此,我创建了函数 f 供 lambda 调用。我认为这些列被重新排序,因为容器是一个 OrderedDict 并且它是按列名称的字典顺序排序的。也许它不一定是 OrderedDict 但这是我在文档中找到的。

关于python - petl - 如何用零替换空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com