I need to rename columns in pandas so that several different column names associated to a pre-defined keyword have their titles replaced by that key word.
I would like that a list of several different potential column names are associated to one key word, which I can then use to later group information. It is not like this problem in Renaming columns in pandas as this does not address the use of multiple column names that can be associated to one keyword.
For instance: cats, dogs, birds, fish -> are replaced with the title "animals"
I was looking at the rename function HERE and HERE , however, it does not seem to take into account the possibility to have multiple columns be associated to a key word to rename.
Is this posisble to do within pandas?
My (not-working) attempt so far is as follows:
newNames = {
'animals':['cats','dogs','fish'],
'colors':['red','blue','green']
}
sample df:
cats dogs fish red
1 2 3 2
2 3 5 4
3 4 3 4
df.rename(index=str,columns=newNames,inplace=True)
desired result:
animals animals animals colors
1 2 3 2
2 3 5 4
3 4 3 4