I have imported a file with no column names (they have defaulted to 0, 1, 2 ...). I want to rename them to Var1, Var2 .. respectively. Have searched the documentation and various sites.
I'm sure this is a simple problem, but please guide me :)
pd.DataFrame.info(thyroidX)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3772 entries, 0 to 3771
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 0 3772 non-null float64
1 1 3772 non-null float64
2 2 3772 non-null float64
3 3 3772 non-null float64
4 4 3772 non-null float64
5 5 3772 non-null float64
dtypes: float64(6)
memory usage: 176.9 KB
thyroidX.rename(columns = {"0" : "Var1", "1" : "Var2", "2" : "Var3", "3" : "Var4", "4" : "Var5",\
"5" : "Var6"}, inplace = True, errors = "raise")
---------------------------------------------------------------
KeyError Traceback (most recent call last)
Input In [39], in <cell line: 6>()
1 # Rename column names before merge
2 # based on https://stackabuse.com/how-to-rename-pandas-dataframe-column-in-python/
3 # x vars
4 #thyroidX.rename(columns = {"0" : "Var1", "1" : "Var2", "2" : "Var3", "3" : "Var4", "4" : "Var5",\
5 # "5" : "Var6"}, inplace = True, errors = "raise")
----> 6 thyroidX.rename({"0" : "Var1", "1" : "Var2", "2" : "Var3", "3" : "Var4", "4" : "Var5",\
7 "5" : "Var6"}, axis = 1, inplace = True, errors = "raise")
.....
KeyError: "['0', '1', '2', '3', '4', '5'] not found in axis"
CodePudding user response:
Try this:
thyroidX.rename(columns = {0 : "Var1", 1 : "Var2", 2 : Var3, 3 : Var4, 4 : "Var5", 5 : "Var6"}, inplace = True, errors = "raise")
or, if all columns are numeric
thyroidX.columns = ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6"]
CodePudding user response:
You need to specify axis=1
to apply to columns