如何将itertate转换为dataframe列并删除特定行?

2024-04-23 20:00:40 发布

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

这是我的csv文件:

A  B  C  D
0  1  5  5
1  0  3  0
0  0  0  0
2  1  3  4 

我要它检查B列如果我foud 0我删除所有的行,所以这就是我需要的输出:

A  B  C  D
0  1  5  5
2  1  3  4

我试过这个代码:

import pandas as pd
df=pd.read_csv('Book1.csv', sep=',', error_bad_lines=False, dtype='unicode')
for index, row in df.iterrows():
    if row['B'] == 0:
        df.drop(row,index=False)
df.to_csv('hello.csv')

它还给了我:

   A  B  C  D
0  0  1  5  5
1  1  0  3  0
2  0  0  0  0
3  2  1  3  4

它没有删除任何东西我不知道哪里有问题 请帮忙


Tags: 文件csv代码importfalsepandasdfread
1条回答
网友
1楼 · 发布于 2024-04-23 20:00:40

您可以检查B中哪些行不等于1,然后执行boolean indexing,结果如下:

df[df.B.ne(0)]

   A  B  C  D
0  0  1  5  5
3  2  1  3  4

请注意,在您的方法中,为了删除给定的行,您需要指定索引,因此您应该执行以下操作:

for index, row in df.iterrows():
    if row['B'] == 0:
        df.drop(index, inplace=True)
df.to_csv('hello.csv')

也不要忘记在删除一行之后重新分配结果。这可以通过将inplace设置为True或重新分配回df来完成

相关问题 更多 >