I have the following dataframe:
data.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 658 entries, 2016-01-04 to 2019-01-31
Data columns (total 4 columns):
Equity 658 non-null float64
Equity 658 non-null float64
Equity 658 non-null float64
Equity 658 non-null float64
dtypes: float64(4)
memory usage: 25.7 KB
I try to rename the columns.
old_names = ['Equity', 'Equity', 'Equity', 'Equity' ]
new_names = ['Equity1','Equity2', 'Equity3','Equity4' ]
data.rename(columns=dict(zip(old_names, new_names)), inplace=True)
It returns the error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-123-9f8bfefe3429> in <module>
1 old_names = ['Equity', 'Equity', 'Equity', 'Equity' ]
2 new_names = ['Equity1','Equity2', 'Equity3','Equity4' ]
----> 3 data.rename(columns=dict(zip(old_names, new_names)), inplace=True)
TypeError: 'dict' object is not callable
What can be the cause?. I will appreciate your help.
A dictionary is a perfectly valid object for the argument
columns
ofpandas.DataFrame.rename
. Your error is almost certainly due to the fact that before these lines in your module you have redefined the built-in type (class)dict
. It's very easy to reproduce your error:With
dict = a
(odict = {}
) you reassigndict
the reference to an object to the identifierdict
, so from now on,dict
it is not a class that you can instantiate to create a new dictionary, it is an object of this class, and a dictionary is not callable ({"a": 4}()
) .As a general rule, you should never use the names of the built-ins or modules of the stdlib to name your own variables, at most (if there is no better name) use the name followed by an underscore as the conventions mark:
That said, even correcting the above, as you are doing, you will not be able to rename the columns:
zip(old_names, new_names)
generate:when we use
dict
over the above we get:This happens because dictionaries have a unique key , so only the last pair, , remains
('Equity', 'Equity4')
. It will finally result in a DataFrame with all columns renamed asEquity4
For your case, just reassign the new names using the attribute
DataFrame.columns
: