Maaz Javed
Maaz Javed

Reputation: 1

Removing a row from CSV file with a condition

I need guidance in how to remove rows having specific values in a column for each row.

For instance, column A has 50 rows and it has value 0 at different places.

I want to remove whole row that has value 0 for column A in a CSV file.

Following is the dataset from which I need to remove rows.

Row1: 1,95,90 Row2: 1,85,76 Row3: 0,100,71 Row4: 0,100,24 Row5: 1,100,76

I have tried .drop command in pandas but its not working.

Here is the code I have developed.

enter image description here

Upvotes: 0

Views: 4460

Answers (3)

westandskif
westandskif

Reputation: 982

If using convtools, then:

from convtools import conversion as c
from convtools.contrib.tables import Table

rows = (
    Table.from_csv("tmp.csv", header=True)
    .filter(c.col("A") != "0")
    .into_csv("tmp-updated.csv")
)

Tables help - https://convtools.readthedocs.io/en/latest/tables.html

Upvotes: 0

Kubra Altun
Kubra Altun

Reputation: 405

You can use the drop function with inplace=True which makes the changes on df itself;

df.drop(0, inplace=True)

Upvotes: 0

Sam
Sam

Reputation: 903

So start by loading the file in pandas:

df = pd.read_csv("name.csv")

Then subset where that condition is not found, i.e. df where df column A does not equal 0:

df = df[df["A"] != 0]

Upvotes: 1

Related Questions