Skip to main content
 首页 » 编程设计

python之从包含 IP 地址的 Pandas df 中删除行

2025年05月04日21over140

我正在处理一个在 pandas df 中看起来像这样的请求 url 数据集(字符串):

df 
  request_url                                  count 
0 https://login.microsoftonline.com            24521 
1 https://dt.adsafeprotected.com               11521 
2 http://209.53.113.23/                        225211 
3 https://googleads.g.doubleclick.net          6252 
4 https://fls-na.amazon.com                    65225  
5 https://v10.vortex-win.data.microsoft.com    7852222  
6 https://ib.adnxs.com                         12 
7 http://177.41.65.207/read.txt                188  

期望的输出:

newdf 
  request_url                                  count 
0 https://login.microsoftonline.com            24521 
1 https://dt.adsafeprotected.com               11521 
2 https://googleads.g.doubleclick.net          6252 
3 https://fls-na.amazon.com                    65225 
4 https://v10.vortex-win.data.microsoft.com    7852222 
5 https://ib.adnxs.com                         12 

然后我将在数据上使用 tld 库。我想摆脱这些的原因是因为 tld 库不知道如何处理域中的 IP。有没有一种简单的方法可以从数据框中删除包含 IP 地址的行?

请您参考如下方法:

您可以使用正则表达式 [0-9]+(?:\.[0-9]+){3}, astype 检查 findall bool 会将所有空列表转换为 False

df[~df.request_url.str.findall(r'[0-9]+(?:\.[0-9]+){3}').astype(bool)] 
Out[908]:  
                                 request_url 
0          https://login.microsoftonline.com 
1             https://dt.adsafeprotected.com 
3        https://googleads.g.doubleclick.net 
4                  https://fls-na.amazon.com 
5  https://v10.vortex-win.data.microsoft.com 
6                       https://ib.adnxs.com