Stefano Fedele Stefano Fedele - 4 months ago 16
Python Question

change column values (and type) to a pandas Dataframe

I am trying to rename a column in a pandas dataframes, but different dataframes have different types of columns and I need an help. An easy example will clarify you my issue.

import pandas as pd
dic1 = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]}
dic2 = {1: [4, 1, 3, 1], 2: [4, 2, 1, 4], 3: [5, 7, 9, 1]}

df1 = pd.DataFrame(dic1)
df2 = pd.DataFrame(dic2)


Now if I type

df1.columns.values[-1] = 'newName'


I can easily change the last column name of the first dataframe, but if I type

df2.columns.values[-1] = 'newName'


I get a message of error from Python as the columns in the second dataframe are of different type. Is there a way to change the type of those columns and/or make Python understand in some ways that even the last column of df2 has to be named 'newName'?

Answer

This isn't the normal method to rename a column, you should use rename to do this:

In [95]:
df2.rename(columns={df2.columns[-1]:'newName'}, inplace=True)
df2

Out[95]:
   1  2  newName
0  4  4        5
1  1  2        7
2  3  1        9
3  1  4        1