Skip to main content
 首页 » 编程设计

python之带有排序列表的 Pandas 列的名字

2025年05月04日23落叶无声

假设我有以下数据框:

df = pd.DataFrame({'AB': [['ab', 'ef', 'bd'], ['abc', 'efg', 'cd'], ['bd', 'aaaa']], 
                   'CD': [['xy', 'gh'], ['trs', 'abc'], ['ab', 'bcd', 'efg']],   
                   'EF': [['uxyz', 'abc'], ['peter', 'adam'], ['ab', 'zz', 'bd']]}) 
 
df 
 
               AB              CD             EF 
0    [ab, ef, bd]        [xy, gh]    [uxyz, abc] 
1  [abc, efg, cd]      [trs, abc]  [peter, adam] 
2      [bd, aaaa]  [ab, bcd, efg]   [ab, zz, bd] 

我想提取包含排序列表的列。在这种情况下,它是 CD,因为 ['ab','bcd','efg'] 是按升序排序的。保证没有列表是空的,并且它至少包含两个元素。我被困在如何使用 Pandas 将 applymap 和 sort 功能组合在一起? 我试图从 here 中找到解决方案但无法找到一种方法来组合 applymap 和 sort。

我正在使用 Python 2.7 和 pandas

请您参考如下方法:

使用 applymap 和 sorted

In [2078]: df.applymap(sorted).eq(df).any() 
Out[2078]: 
AB    False 
CD     True 
EF    False 
dtype: bool 

将结果放入列表

In [2081]: cond = df.applymap(sorted).eq(df).any() 
 
In [2082]: cond[cond].index 
Out[2082]: Index([u'CD'], dtype='object') 
 
In [2083]: cond[cond].index.tolist() 
Out[2083]: ['CD'] 

如果您需要包含数据的特定列

In [2086]: df.loc[:, cond] 
Out[2086]: 
               CD 
0        [xy, gh] 
1      [trs, abc] 
2  [ab, bcd, efg] 

然后,获取列名的第一个

In [2092]: cond[cond].index[0] 
Out[2092]: 'CD'