Skip to main content
 首页 » 编程设计

python之如何检查 pandas 中的列是否以 a 或 b 结尾

2024年12月31日12lidabo

我需要按最后一个字符过滤列,针对多个字符进行测试。

import numpy as np 
import pandas as pd 
 
df = pd.read_table("F:\\bridges.txt", names = ['IDENTIF','RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH', 'LANES',  
 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE'])  
 
print(df.columns[df.columns.str.endswith('N' or 'H' or 's') ]) 

输出:

Index(['LOCATION', 'SPAN'], dtype='object') 

这里我没有得到所有以 N、H 或 s 结尾的列。

请您参考如下方法:

您可以使用 pd.Index.str.endswith带有一个元组,然后是 bool 索引:

L = ['IDENTIF','RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH', 
     'LANES', 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE'] 
 
df = pd.DataFrame(columns=L) 
 
cols = df.columns[df.columns.str.endswith(tuple('HNS'))] 
 
Index(['LOCATION', 'LENGTH', 'LANES', 'SPAN'], dtype='object') 

该功能模仿 Python 的内置 str.endswith ,它允许您提供一个 tuple 来匹配多个项目作为替代条件。