简体   繁体   中英

How can I drop rows with certain values from a dataframe?

I'm taking two different datasets and merging them into a single data frame, but I need to take one of the columns ('Presunto Responsable') of the resulting data frame and remove the rows with the value 'Desconocido' in it.

This is my code so far:

#%% Get data

def getData(path_A, path_B):
    victims = pd.read_excel(path_A)
    dfv = pd.DataFrame(data=victims)
    cases = pd.read_excel(path_B)
    dfc = pd.DataFrame(data=cases)
    return dfv, dfc

#%% merge dataframes

def mergeData(data_A, data_B):
    data = pd.DataFrame()
    #merge dataframe avoiding duplicated colums
    cols_to_use = data_B.columns.difference(data_A.columns)  
    data = pd.merge(data_A, data_B[cols_to_use], left_index=True, right_index=True, how='outer') 
    cols_at_end = ['Presunto Responsable']
    #Take 'Presunto Responsable' at the end of the dataframe
    data = data[[c for c in data if c not in cols_at_end] 
    + [c for c in cols_at_end if c in data]]
    return data

#%% Drop 'Desconocido' values in 'Presunto Responsable'

def dropData(data):
    indexNames = data[data['Presunto Responsable'] == 'Desconocido'].index
    for c in indexNames:
    data.drop(indexNames , inplace=True)
    return data

The resulting dataframe still has the rows with 'Desconocido' values in them. What am I doing wrong?

You can just say:

data = data[data['Presunto Responsable'] != 'Desconocido']

Also, btw, when you do pd.read_excel() it creates a dataframe, you don't need to then pass that into pd.DataFrame() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM