Reputation: 651
I am borrowing this example from here. I have a dataframe like this:
# Import pandas package
import pandas as pd
# Define a dictionary containing ICC rankings
rankings = {'test': ['India', 'South Africa', 'England',
'New Zealand', 'Australia'],
'odi': ['England', 'India', 'New Zealand',
'South Africa', 'Pakistan'],
't20': ['Pakistan', 'India', 'Australia',
'England', 'New Zealand']}
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
# Before renaming the columns
print(rankings_pd)
test odi t20
0 India England Pakistan
1 South Africa India India
2 England New Zealand Australia
3 New Zealand South Africa England
4 Australia Pakistan New Zealand
Now let's say I want to change the name of the 1st and 2nd columns. This is what I am trying:
rankings_pd[rankings_pd.columns[0:2]].columns = ['tes_after_change', 'odi_after_change']
print(rankings_pd[rankings_pd.columns[0:2]].columns)
Index(['test', 'odi'], dtype='object')
But this seems to return exactly the same columns names and not changing them.
Upvotes: 3
Views: 198
Reputation: 24304
Just use rename()
method and pass the dictionary
of old values and new values as key-value pair in columns parameter:-
rankings_pd=rankings_pd.rename(columns={'test':'tes_after_change','odi':'odi_after_change'})
Edit by @sammywemmy
:
You could extend the idea with an anonymous function :
rankings_pd.rename(columns= lambda df: f"{df}_after_change" if df in ("test", "odi") else df)
Upvotes: 8
Reputation: 75080
You can use to_numpy()
and replace the slice:
rankings_pd.columns.to_numpy()[0:2] = ['tes_after_change', 'odi_after_change']
rankings_pd.columns
#Index(['tes_after_change', 'odi_after_change', 't20'], dtype='object')
Or using np.r_
with df.rename
rankings_pd.rename(dict(zip(rankings_pd.columns[np.r_[0:2]],
['tes_after_change', 'odi_after_change'])),axis=1)
Upvotes: 4
Reputation: 150735
You should/could not replace part of the columns
. You need to replace them all at once:
rankings_pd.columns = ['tes_after_change', 'odi_after_change'] + rankings_pd.columns[2:].tolist()
Upvotes: 4