Skip to main content
 首页 » 编程设计

python Pandas : case insensitive drop column

2024年10月25日11zhwl

我有一个 df,我想按标签删除一列,但不区分大小写。注意:我不想更改我的 df 中的任何内容,所以我想避免使用“str.lower”。

这是我的 df:

print df  
 
Name UnweightedBase  Base     q6a1    q6a2    q6a3    q6a4    q6a5   q6a6 eSubTotal 
Name                                                                                
Base           1006  1006  100,00%  96,81%  96,81%  96,81%  96,81%  3,19%   490,44% 
q6_6             31    32  100,00%       -       -       -       -      -         - 
q6_3           1006  1006   43,44%  26,08%  13,73%   9,22%   4,34%  3,19%   100,00% 
q6_4           1006  1006   31,78%  31,71%  20,09%  10,37%   2,87%  3,19%   100,00% 

我可以对下面的代码应用任何魔法吗?

df.drop(['unWeightedbase', 'Q6A1'],1) 

请您参考如下方法:

我认为你可以做的是创建一个函数来为你执行不区分大小写的搜索:

In [90]: 
# create a noddy df 
df = pd.DataFrame({'UnweightedBase':np.arange(5)}) 
print(df.columns) 
# create a list of the column names 
col_list = list(df) 
# define our function to perform the case-insensitive search 
def find_col_name(name): 
    try: 
        # this uses a generator to find the index if it matches, will raise an exception if not found 
        return col_list[next(i for i,v in enumerate(col_list) if v.lower() == name)] 
    except: 
        return '' 
df.drop(find_col_name('unweightedbase'),1) 
Index(['UnweightedBase'], dtype='object') 
Out[90]: 
Empty DataFrame 
Columns: [] 
Index: [0, 1, 2, 3, 4] 

我的搜索代码归因于这个SO:find the index of a string ignoring cases