Skip to main content
 首页 » 编程设计

python之Pandas 和元组检查

2025年05月04日20youxin

df = pd.DataFrame({'num_legs': [2, 4, 8, 0], 
                   'num_wings': [2, 0, 0, 0], 
                   'num_specimen_seen': [10, 2, 1, 8]}, 
                   index=['falcon', 'dog', 'spider', 'fish']) 

其中 num_legs、num_wings 和 num_specimen_seen 是列。

现在,我有像 ('num_wings', 'num_legs') 这样的元组,想检查是否有值是 df 列?如果是,则返回 true,否则返回 false。

('num_wings', 'num_legs') -> 这将返回 true ('abc', 'num_legs') -> 错误

请您参考如下方法:

你可以在这里使用get_indexer。


idxr = df.columns.get_indexer(tup) 
all(idxr>-1) 

性能

cols = pd.Index(np.arange(10_000)) 
tup = tuple(np.arange(10_001)) 
 
%timeit all(cols.get_indexer(tup)>-1) 
3.86 ms ± 87.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 
 
%timeit all(e in cols for e in tup) 
5.96 ms ± 69.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)