【发布时间】:2018-10-01 16:21:25
【问题描述】:
我有一个 Pandas 数据框,其中包含单次出售口香糖、巧克力和薄荷糖的事件。它们被汇总并按周数排序。我现在将其翻译成文本,然后通过电子邮件发送,取消以下方法:
pd['text'] = 'In calendar week (' + pd['weeknumber'].map(str) + '), customers have bought ' + pd['gummibears'].map(str) + 'kg of gummibears, ' + pd['chocolate'].map(str) + 'kg of chocolate, as well as ' + pd['mint'].map(str) + 'kg of mints.'
理想情况下,结果会给出一个很好的文本来概述销售情况。但是,有可能 0 公斤已售出,当然也会出现,看起来像这样:
>>> "In calendar week 25, customers have bought 0kg of gummibears, 25kg of chocolate, as well as 0kg of mints."
>>> "In calendar week 26, customers have bought 6kg of gummibears, 0kg of chocolate, as well as 2kg of mints."
这可行,但会让读者感到困惑。有没有一种优雅的方法可以过滤掉所有 0kg 的实例而不嵌套多个循环?最好是上面的结果如下所示:
>>> "In calendar week 25, customers have bought 25kg of chocolate."
>>> "In calendar week 26, customers have bought 6kg of gummibears, as well as 2kg of mints."
【问题讨论】:
-
gb_count = '' if pd['gummibears'] > 0: gb_count = '客户已购买' + pd['gummibears'].map(str) + 'kg of gummibears,'跨度>
标签: python pandas loops filtering