删除数据框中的行,直到它用python找到某个值为止

2024-09-19 20:59:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我需要这段代码来不断删除行,直到A1单元格是一个特定的字符串,我尝试了以下方法:

while table[0][0] != 'Nº TAD':
    table = table.drop(table.index[0])

但似乎循环的次数比我想要的要多,我不知道为什么


Tags: 方法字符串代码indexa1table次数drop
2条回答

这正是你想要的。只需将if检查与要检查的string交换即可df是你的{}

In[16]: df
Out[16]: 
   0  1  2  3
0  1  2  3  4
1  1  2  3  4
2  1  2  3  4
3  5  6  7  8

In[17]: new_df = df
   ...: for num, row in enumerate(df.values):
   ...:     if row[0] == 5:
   ...:         break
   ...:     else:
   ...:         new_df = new_df.drop(num)
   ...:   
  
In[18]: new_df
Out[18]: 
   0  1  2  3
3  5  6  7  8

您可以按如下方式创建行:

for index, row in table.iterrows():
   if row["col_name"] == 'Nº TAD':
        break
   table.drop([index],inplace=True)

相关问题 更多 >