如何在pandas数据框的df.iterrows()过程中删除当前行?

33

我想在迭代中使用 df.iterrows(), 如果某一行的特定列不满足我的 if 条件,则删除当前行。

例如:

for index, row in df:
     if row['A'] == 0:
          #remove/drop this row from the df
          del df[index] #I tried this but it gives me an error

这可能是一个非常简单的问题,但我仍然无法弄清楚如何做到这一点。非常感谢您的帮助!

2个回答

70

我不知道这是否是伪代码,但是你不能像这样删除一行数据,你可以使用drop命令:


In [425]:

df = pd.DataFrame({'a':np.random.randn(5), 'b':np.random.randn(5)})
df
Out[425]:
          a         b
0 -1.348112  0.583603
1  0.174836  1.211774
2 -2.054173  0.148201
3 -0.589193 -0.369813
4 -1.156423 -0.967516
In [426]:

for index, row in df.iterrows():
    if row['a'] > 0:
        df.drop(index, inplace=True)
In [427]:

df
Out[427]:
          a         b
0 -1.348112  0.583603
2 -2.054173  0.148201
3 -0.589193 -0.369813
4 -1.156423 -0.967516

如果您只想过滤掉这些行,可以执行布尔索引:

df[df['a'] <=0]

能够达到相同的效果


0

我尝试了@EdChum的解决方案,使用自定义的pandas.DataFrame,但是出现了错误:KeyError: '[78] not found in axis'。如果你遇到了同样的错误,可以通过在每个.iterrows()迭代中删除数据帧的索引来修复它。

使用的数据框来自investpy,其中包含所有在Investing.com上进行索引的股票数据,打印函数是在pprint中实现的。无论如何,这是使其工作的代码片段:

In [1]:

import investpy
from pprint import pprint

In [2]:

df = investpy.get_equities()

pprint(df.head())

Out [2]:

     country               name                           full_name  \
0  argentina            Tenaris                             Tenaris   
1  argentina       PETROBRAS ON     Petroleo Brasileiro - Petrobras   
2  argentina     GP Fin Galicia          Grupo Financiero Galicia B   
3  argentina  Ternium Argentina  Ternium Argentina Sociedad Anónima   
4  argentina      Pampa Energía                  Pampa Energía S.A.   

                      tag          isin     id currency  
0       tenaris?cid=13302  LU0156801721  13302      ARS  
1  petrobras-on?cid=13303  BRPETRACNOR9  13303      ARS  
2          gp-fin-galicia  ARP495251018  13304      ARS  
3                 siderar  ARSIDE010029  13305      ARS  
4           pampa-energia  ARP432631215  13306      ARS  

In [3]:

pprint(df[df['tag'] == 'koninklijke-philips-electronics'])

Out [3]:

      country                     name                   full_name  \
78  argentina  Koninklijke Philips DRC  Koninklijke Philips NV DRC   

                                tag          isin     id currency  
78  koninklijke-philips-electronics  ARDEUT110558  30044      ARS  

In [4]:

for index, row in df.iterrows():
    if row['tag'] == 'koninklijke-philips-electronics':
        df.drop(df.index[index], inplace=True)

In [5]:

pprint(df[df['tag'] == 'koninklijke-philips-electronics'])

Out [5]:

Empty DataFrame
Columns: [country, name, full_name, tag, isin, id, currency]
Index: []

希望这能对某个人有所帮助!同时感谢原始答案@EdChum


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接