Home > Enterprise >  How to Compare and delete Rows from a CSV file in Pandas?
How to Compare and delete Rows from a CSV file in Pandas?

Time:11-24

This is what the CSV file looks like : enter image description here

How to delete all the title, description rows, except leaving the 1st one . I am using Pandas as of now, so a solutions based on it will be helpful.

This is what I tried, but it didnt worked :

df = pd.read_csv(file)
df =  df[df.name = "title"] 
df.to_csv(file, index=False)

CodePudding user response:

You can keep the rows where the title is not 'title' :

df =  df[df['title'] != "title"] 

CodePudding user response:

Firstly find the indexes of title and description

index_list = df.index[df['title'] == 'title' or 
             df['description'] == 'description'].tolist()

Now drop all the rows that contain title and description.

df.drop(index=index_list, inplace=True)

At last write the data-frame in file

df.to_csv(file_name, index=False)

CodePudding user response:

Hopefully the first title,description are assigned as headers of the dataframe.

In any case, you can use df.drop() with some added zing to drop certain rows that meet your criteria:

Input:


    title   desc
0   abc2    something1
1   title   desc
2   abc2    something2
3   title   desc
4   abc3    something3

Using criteria where any row's title is literally called "title" and dropping them:

df = df.drop(df[df.title == "title"].index)

Output:

    title   desc
0   abc2    something1
2   abc2    something2
4   abc3    something3
  • Related