Filtering Python Pandas dataframe by IP octet

Viewed 27

I have been Goog'ling this for a while, but haven't found the solution, so a hint in the right direction would be appreciated...

I have a Pandas dataframe with roughly 13.000 rows with 96 columns. One of the columns contains IP addresses that I would like to filter on.

I would like to remove all rows where the IP address matches these any of these: 10.x.220.x or 10.x.240.x

1 Answers

Use boolean indexing with a regex and str.fullmatch:

df2 = df[~df['ip_column'].str.fullmatch(r'10\.\d+\.(220|240)\.\d+')]

Example input:

  col     ip_column
0   A    10.1.220.1
1   B      10.0.0.1
2   C  10.127.240.0
3   D     127.0.0.1

Matching output:

  col  ip_column
1   B   10.0.0.1
3   D  127.0.0.1

regex:

10           # match 10
\.           # match a dot
\d+          # match one or more digits
\.           # match a dot
(220|240)    # match 220 or 240
\.           # match a dot
\d+          # match one or more digits
Related