【问题标题】:Avoid overwriting dataset in Python forloop避免在 Python forloop 中覆盖数据集
【发布时间】:2020-11-21 23:00:16
【问题描述】:
price
date            price      fruit
2010-01-04    0.83        banana
2010-01-04    0.05         apple

对于每个水果,如果那个水果==True,你怎么能保留,然后在处理那个特定水果时暂时放下水果列?

listxx = [(price, "price")]
fruits = ['apple', 'banana', 'pear']

for fruit in fruits:
    for x, y in listxx:
            x[x['fruit'] == fruit]
            x.drop(['fruit'], axis=1, inplace=True)

目前,当我到达香蕉时,由于苹果,水果列已经被删除。

对香蕉进行迭代时,价格数据集应如下所示:

date          price     
2010-01-04    0.83     

当迭代苹果时,价格数据集应该是:

date            price    
2010-01-04    0.05       

【问题讨论】:

  • 问题不明确,如果你打算删除水果列或行。
  • 你能否准确地显示给定输入的输出应该是什么样的线,并使输出足够大以显示问题(即,包括应该和不被删除的东西)?跨度>
  • 它需要对每个水果进行迭代。代码中断是因为在到达列表中的第二个项目时没有可删除的水果列。保留 iffruit=True 和删除fruit 列是暂时的。
  • 这部分:x[x['fruit'] == fruit] 创建一个 new 表,其中仅包含 fruit 匹配的行,然后 将其丢弃,没有任何意义我>。特别是,下一行的x 指的是原始 price 表。
  • "它需要对每个水果进行迭代。"这几乎没有足够的信息。在迭代期间应该发生什么?似乎您想找到水果匹配的行,并考虑那些没有水果列的行,然后......然后呢?您是否尝试更改 price 数据框的内容?

标签: python python-3.x pandas dataframe for-loop


【解决方案1】:

如果水果 = 那个水果,我需要价格数据集来临时删除固定列并保留。然后回到原始数据集,让下一个水果做同样的事情。

实际上,这意味着用过滤后的数据制作一个数据集。我们将给它一个单独的名称,以便我们可以 i) 实际上引用检查行的结果,并且 ii) 从该结果中删除列,而不是原始结果。

我们还将努力以一种易于理解的方式命名事物。

tables_and_names = [(price, "price")]
fruits = ['apple', 'banana', 'pear']

for fruit in fruits:
    for table, name in tables_and_names:
        filtered_table = table[table['fruit'] == fruit]
        filtered_table.drop(['fruit'], axis=1, inplace=True)
        # now we can do more logic with the filtered_table

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2014-12-04
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多