Home > Enterprise >  Filter integer column endswith hundreds in Python
Filter integer column endswith hundreds in Python

Time:09-23

Given a small dataset df as follows:

[{'id': 110000, 'name': 'Derek Wood'},
 {'id': 110101, 'name': 'Thomas Butler'},
 {'id': 110105, 'name': 'Nicholas Crawford'},
 {'id': 120000, 'name': 'Brian Jenkins'},
 {'id': 120101, 'name': 'Eric Stokes'},
 {'id': 220000, 'name': 'Christopher Mccarty'},
 {'id': 220100, 'name': 'Christian Griffith'},
 {'id': 220102, 'name': 'Antonio Webb'}]

or:

       id                 name
0  110000           Derek Wood
1  110101        Thomas Butler
2  110105    Nicholas Crawford
3  120000        Brian Jenkins
4  120101          Eric Stokes
5  220000  Christopher Mccarty
6  220100   Christian Griffith
7  220102         Antonio Webb

How could filter id endswith hundreds? The expected result will like:

       id                 name
0  110000           Derek Wood
3  120000        Brian Jenkins
5  220000  Christopher Mccarty
6  220100   Christian Griffith

My trial code, it works but I'm looking for a alternative solution without converting the dtype of id:

df['id'] = df['id'].astype(str)
df[df['id'].str.endswith('00')]

CodePudding user response:

Try using modulus which is % in pandas. It returns the remainder value after division. For your use case, you want to return the rows of id divided by 100 and its remainder is 0.

condition = (df["id"]%100 == 0)
resulted_df = df[condition]
  • Related