Trying_hard Trying_hard - 1 year ago 82
Python Question

Pandas filter dataframe off sliced value

I have the following dataframe

names brand
A7 Audi
TrailBlazer Chevy
RS8 Audi
Tahoe Chevy
Corvette Chevy
GL450 Mercedes


I would like to filter the df off of a slice of the names column. I want to use the last character of the value. If the the last character is a digit I want to 'ignore' that and return only the other results.

I am trying this.

new_df = df[(df['names'] == (lambda x: x['names'].str[-1]).isdigit())]


When I do this it returns a empty dataframe.

I would expect to return this.

names brand
TrailBlazer Chevy
Tahoe Chevy
Corvette Chevy

Answer Source

You can use str[-1] to access the last character of the strings, and use str.isdigit() to test the condition:

df[~df.names.str[-1].str.isdigit()]
#         names   brand
#1  TrailBlazer   Chevy
#3        Tahoe   Chevy
#4     Corvette   Chevy

Or more safely, in case you have numeric values in the names column:

df[~df.names.astype(str).str[-1].str.isdigit()]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download