Appending list from dataframe with for statement

Viewed 37

In school learning Python. Working on a project and I wanted to remove specific rows from one dataframe and turn it into another dataframe. I have a list of 372 animals and if their names show up in the dataframe (which has 1288 rows where each row is a different animal), I want to remove the row. So, I found a solution to remove the rows:

ess_aza = []

for i in aza_names:
    if True:
        ess_aza.append(ess_clean.loc[ess_clean['scientific_name'] == i])
    else:
        return

What the list looks like when it's printed is this:

[Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [],   common_name      scientific_name      status
0       Addax  Addax nasomaculatus  Endangered, Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [],           common_name     scientific_name      status
1  Alligator, Chinese  Alligator sinensis  Endangered,      common_name         scientific_name      status
1  Anoa, lowland  Bubalus depressicornis  Endangered, Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], Empty DataFrame
Columns: [common_name, scientific_name, status]
Index: [], ,....

I don't know enough about Python to know why it's giving me that output. From what I can gather, it is returning data from all 1288 rows and returning 'Empty DataFrame Columns: [common_name, scientific_name, status] Index: []' for all the rows that don't match the list.

How can I stop that from happening and just append a list with the rows I need? (Or better yet just create a new dataframe with just the rows I need. That's the end goal.)

1 Answers

If you have a list of rows to exclude, then try this:

clean_df = df[~df['scientific_name'].isin(excludeRows)]

To get a df of the excluded rows

clean_df = df[df['scientific_name'].isin(excludeRows)]

clean_df is your new df, df is old one and excludeRows are thr row values to exclude.

Related