df.rename(columns) 返回 KeyError: ..值。。在轴中找不到"



我导入了一个没有列名的文件(它们默认为0、1、2…(。我想将它们重命名为Var1、Var2。。分别地已经搜索了文档和各种网站。

我确信这是一个简单的问题,但请指导我:(

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" 

试试这个:

thyroidX.rename(columns = {0 : "Var1", 1 : "Var2", 2 : Var3, 3 : Var4, 4 : "Var5", 5 : "Var6"}, inplace = True, errors = "raise")

或者,如果所有列都是数字

thyroidX.columns = ["Var1",  "Var2", "Var3", "Var4", "Var5",  "Var6"]

您需要指定axis=1以应用于列

最新更新