I have DataFrame in Python Pandas like below (my real DF has many many more columns):
Input data:
COL1 | col2 | col3
------|--------|-------
X | 11 | 2021
Y | 22 | 1990
Requirements:
And I need to make upper each column names in DataFrame except column names from list below if columns from list exists:
list_not_to_up = ["col2", "col55"]
my code is:
df.columns = [x.upper() if x not in df[list_not_to_up].columns else x for x in df.columns]
Nevertheless I have error: KeyError: "['col55'] not in index"
Desire output:
COL1 | col2 | COL3
------|--------|-------
X | 11 | 2021
Y | 22 | 1990
How to modify my code so as to upper all columns from DataFrame except columns from list if of course columns from list exists in DataFrame in Python Pandas?
You can try to rename
on the column difference
:
df.rename(columns={c: c.upper() for c in df.columns.difference(list_not_to_up)})
Output:
COL1 col2 COL3
0 X 11 2021
1 Y 22 1990