我在 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
如果列表中的列当然存在于 Python Pandas 中的 DataFrame 中,如何修改我的代码以便将 DataFrame 中除列表中的列之外的所有列置于上方?
rename
上专栏difference
:
df.rename(columns={c: c.upper() for c in df.columns.difference(list_not_to_up)})
输出:
COL1 col2 COL3
0 X 11 2021
1 Y 22 1990