简体   繁体   English

避免在 Python forloop 中覆盖数据集

[英]Avoid overwriting dataset in Python forloop

price
date            price      fruit
2010-01-04    0.83        banana
2010-01-04    0.05         apple

For each fruit, how could you keep if that fruit ==True, and then drop the fruit column temporarily when dealing with that particular fruit?对于每个水果,如果那个水果 ==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)

Currently, when I get to banana, the fruit column is already deleted because of apple.目前,当我到达香蕉时,由于苹果,水果列已经被删除。

When iterating over banana, the price dataset should look be:迭代香蕉时,价格数据集应如下所示:

date          price     
2010-01-04    0.83     

When iterating over apple, the price dataset should look be:迭代苹果时,价格数据集应该是:

date            price    
2010-01-04    0.05       

I need the price dataset to temporarily remove firm column and keep if fruit = that fruit.我需要价格数据集来临时删除固定列并保留如果水果 = 那个水果。 Then go back to the original dataset for the next fruit to do the same.然后 go 回到原始数据集为下一个水果做同样的事情。

Practically speaking, this means making a new dataset with the filtered data.实际上,这意味着使用过滤后的数据创建一个数据集。 We'll give it a separate name, so that we can i) actually refer to the result from checking the rows, and ii) drop the columns from that result, instead of the original result.我们将给它一个单独的名称,以便我们可以 i) 实际上引用检查行的结果,并且 ii) 从该结果中删除列,而不是原始结果。

We'll also put some effort into naming things in a way that makes it easy to understand what's what.我们还将努力以一种易于理解的方式命名事物。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM