Python Pandas:如何将DataFrame列名转大写且排除存在的指定列
问题场景
我在Python Pandas中有如下DataFrame(实际DF包含更多列):
输入数据:
COL1 | col2 | col3 ------|--------|------- X | 11 | 2021 Y | 22 | 1990
需求:
将DataFrame中除以下列表内的列名外,其余所有列名转为大写:
list_not_to_up = ["col2", "col55"]
我编写的代码如下:
df.columns = [x.upper() if x not in df[list_not_to_up].columns else x for x in df.columns]
运行时报错:KeyError: "['col55'] not in index"
期望输出:
COL1 | col2 | COL3 ------|--------|------- X | 11 | 2021 Y | 22 | 1990
请问如何修改代码实现需求?
解决方案
错误原因
你写的df[list_not_to_up]会尝试从DataFrame中提取列表里的所有列,但col55并不存在于当前DF的列中,因此触发KeyError。根本不需要先筛选DF的列,直接判断当前列名是否在保护列表里即可。
修正后的简洁代码
直接遍历DF的列名,判断每个列名是否在保护列表中,不在则转大写:
list_not_to_up = ["col2", "col55"] df.columns = [x.upper() if x not in list_not_to_up else x for x in df.columns]
可选的严谨写法
如果保护列表包含大量不存在于DF的列,可先取保护列表和DF列的交集,只针对实际存在的列做保留小写处理:
list_not_to_up = ["col2", "col55"] # 过滤出保护列表中实际存在于DF的列 exclude_cols = set(list_not_to_up) & set(df.columns) df.columns = [x.upper() if x not in exclude_cols else x for x in df.columns]
两种写法都能得到期望结果,第一种更简洁,第二种在保护列表规模较大时效率更高。
内容的提问来源于stack exchange,提问作者dingaro
相关产品推荐
相关产品推荐

