python pandas:不区分大小写的删除列

2024-09-30 18:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df,我想逐个删除一个列,但不区分大小写。注意:我不想更改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%

有什么魔力可以应用到下面的代码中吗?在

^{pr2}$

Tags: 数据name内容dfbase区分printq6
1条回答
网友
1楼 · 发布于 2024-09-30 18:15:52

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

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 one:find the index of a string ignoring cases

相关问题 更多 >