Home > Net >  How to rename column header that is a numerical value instead of a string in python/pandas?
How to rename column header that is a numerical value instead of a string in python/pandas?

Time:03-08

I have a column that's named '207', and I want to replace it with a string, say "thing". I've tried to follow nearly every method mentioned here (Rename specific column(s) in pandas) but I can't seem to get it to work? My assumption is that it's treating the 207 as a number and not as a string, so it won't change the name? But I'm not completely sure. Could someone suggest a way to either change the 207 to a string, or to somehow actually replace the column name?

Thank you!

CodePudding user response:

You can check how looks columns names in list:

print (df.columns.tolist())

And then rename, e.g. if 207 is number:

df.rename(columns={207:'thing'})

CodePudding user response:

Sincerely it depends on what it is. Here is an all season thing for you

Data

foo = {
    "country" : ["United States", "Canada", "Japan", "Australia"],
    "code_207" : [7, 2, 1, 4],207 : [7, 2, 1, 4],'207' : [7, 2, 1, 4]
}

df_1 = pd.DataFrame(foo)

        country  code_207  207  207
0  United States         7    7    7
1         Canada         2    2    2
2          Japan         1    1    1
3      Australia         4    4    4

Solution

#Select all columns whether string or integer that contain 207 into a list
cols = list(df_1.filter(regex='207',axis=1).columns)

#For each element in a list above, replace 207 with thing
cols1 = [re.sub('\d ', 'thing', str(a)) for a in cols]

#rename using a wild card
df_1.rename(columns=dict(zip(cols,cols1)), inplace=True)

Outcome

          country  code_thing  thing  thing
0  United States           7      7      7
1         Canada           2      2      2
2          Japan           1      1      1
3      Australia           4      4      4
  • Related