使用for循环在pandas数据框中进行筛选。

huangapple go评论85阅读模式
英文:

Using for loop for filtering in pandas dataframe

问题

我有一个名为'final'的大型数据集,我有一个名为'bn_stocks'的列表要进行筛选。筛选必须应用于'final'(数据集)的"SYMBOL"列。我尝试使用for循环,但只得到了列表的最后一个项目被筛选。

bn_stocks = ['HDFCBANK','ICICIBANK','AXISBANK','KOTAKBANK','SBIN','INDUSINDBK','BANKBARODA','AUBANK','FEDERALBANK',
             'IDFCFIRSTB','BANDHANBK','PNB']
for bn_stock in bn_stocks :
    filt4 = final['SYMBOL'] == bn_stock
    a = final[filt4]

当我运行上面的代码时,我只得到了最后一个元素'PNB'被筛选,而我需要筛选列表'bn_stocks'中的所有元素。

英文:

I have a large dataset 'final' and I have item to filter in a list named 'bn_stocks'. The filtering has to be applied on "SYMBOL" column of 'final'(dataset). I tried using for loop but I only got last item of the list filtered.

bn_stocks = ['HDFCBANK','ICICIBANK','AXISBANK','KOTAKBANK','SBIN','INDUSINDBK','BANKBARODA','AUBANK','FEDERALBANK',
             'IDFCFIRSTB','BANDHANBK','PNB']
for bn_stock in bn_stocks :
    filt4 = final['SYMBOL'] == bn_stock
    a = final[filt4]

when I run the above code I only get the last element filtered 'PNB' , whereas I require it to filter all the elements in the list 'bn_stocks'.

答案1

得分: 2

使用pandas的目的是利用其功能,在99%的用例中,您不使用for-loop来处理数据框。

import pandas as pd

bn_stocks = ['HDFCBANK', 'ICICIBANK', 'AXISBANK', 'KOTAKBANK', 'SBIN',
             'INDUSINDBK', 'BANKBARODA', 'AUBANK', 'FEDERALBANK',
             'IDFCFIRSTB', 'BANDHANBK', 'PNB']

final = pd.DataFrame({
    "value": [1, 2, 3, 4, 5],
    "SYMBOL": ["AXISBANK", "A", "B", "AUBANK", "PNB"]
})

filtered = final[final["SYMBOL"].isin(bn_stocks)]
print(filtered)
英文:

The purpose of using pandas, is to use its power, in 99% of usecases you don't use a for-loop to do something with a dataframe

import pandas as pd

bn_stocks = ['HDFCBANK', 'ICICIBANK', 'AXISBANK', 'KOTAKBANK', 'SBIN',
             'INDUSINDBK', 'BANKBARODA', 'AUBANK', 'FEDERALBANK',
             'IDFCFIRSTB', 'BANDHANBK', 'PNB']

final = pd.DataFrame({
    "value": [1, 2, 3, 4, 5],
    "SYMBOL": ["AXISBANK", "A", "B", "AUBANK", "PNB"]
})

filtered = final[final["SYMBOL"].isin(bn_stocks)]
print(filtered)

huangapple
  • 本文由 发表于 2023年6月25日 21:27:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定