避免覆盖Python forloop中的数据集


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

对于每种水果,如果该水果==为真,你怎么能保留,然后在处理该特定水果时暂时放下果柱?

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=that fruit。然后返回到下一个水果的原始数据集进行同样的操作。

实际上,这意味着用过滤后的数据创建一个新的数据集。我们将给它一个单独的名称,这样我们就可以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

最新更新