Reputation: 861
How do I change the case for data frame columns that are in a list? I know how to make all columns upper case but I don't know how to only make specific columns upper case.
d = {'name':['bob','john','sue'],'id':[545,689,143],'fte':[1,.5,.75]}
df = pd.DataFrame(d)
# list of columns I want to make upper case
cols = ['id','fte']
This doesn't do anything (no error and case isn't changed):
df[cols].rename(str.upper,axis=1,inplace=True)
df
name id fte
0 bob 545 1.00
1 john 689 0.50
2 sue 143 0.75
Upvotes: 2
Views: 387
Reputation: 988
First you can create a map:
# create map manually
col_map = {"id": "ID", "fte": "FTE"}
# or create map automatically
col_map = {item:item.upper() for item in list(df.columns)[1:]}
Then replace the columns index:
df = df.rename(columns=col_map)
Upvotes: 0
Reputation: 323276
IIUC
df.rename(columns=dict(zip(cols,list(map(str.upper,cols)))))
Out[1135]:
name ID FTE
0 bob 545 1.00
1 john 689 0.50
2 sue 143 0.75
Upvotes: 4
Reputation: 3097
You could also use rename
as follows
import pandas as pd
d = {'name':['bob','john','sue'],'id':[545,689,143],'fte':[1,.5,.75]}
df = pd.DataFrame(d)
# list of columns I want to make upper case
cols = ['id','fte']
newColumns = {oldName: oldName.upper() for oldName in cols}
df.rename(columns=newColumns, inplace=True)
print(df)
Upvotes: 2
Reputation: 88236
It won't work the way you're trying to do it, the reason being that indices do not support mutable operations. So one thing you could do is to use a list comprehension to generate a new list of column names an reassign it to df.columns
:
df.columns = [i.upper() if i in cols else i for i in df.columns]
print(df.columns)
# Index(['name', 'ID', 'FTE'], dtype='object')
Upvotes: 5