Let's say I have a dataframe with 10 columns, and I want to convert to upper case the name of just the columns 3 to 7. How could I do that ?
Thanks!
CodePudding user response:
Append new uppercase col list to the unchanged part and assign it to the dataframe
df = pd.DataFrame(columns=['a','b','c'])
df.columns = list(df.columns[0:1]) [x.upper() for x in df.columns[1:]]
Outputs columns as a, B, C
CodePudding user response:
How to upper()
column names/headers based on their index (one or multiple):
df = pd.DataFrame({'test1234':[100,50,10], 'abc_!-?':[200,75,5], 'Column3':[50,300,60]})
df
index | test1234 | abc_!-? | Column3 |
---|---|---|---|
0 | 100 | 200 | 50 |
1 | 50 | 75 | 300 |
2 | 10 | 5 | 60 |
df.columns = [x.upper() if x in df.columns[0:2] else x for x in df.columns]
df
index | TEST1234 | ABC_!-? | Column3 |
---|---|---|---|
0 | 100 | 200 | 50 |
1 | 50 | 75 | 300 |
2 | 10 | 5 | 60 |
How to upper()
column names/headers based on their names (one or multiple):
df = pd.DataFrame({'col1':[100,50,10], 'col2':[200,75,5], 'col3':[50,300,60]})
df
index | col1 | col2 | col3 |
---|---|---|---|
0 | 100 | 200 | 50 |
1 | 50 | 75 | 300 |
2 | 10 | 5 | 60 |
df.columns = [x.upper() if x in df[['col1','col2']].columns else x for x in df.columns]
df
index | COL1 | COL2 | col3 |
---|---|---|---|
0 | 100 | 200 | 50 |
1 | 50 | 75 | 300 |
2 | 10 | 5 | 60 |