我有一个 pandas 数据框('df3'),我想重命名其中的列。它是另一个数据框的子集,我正在 jupyter 笔记本中工作。
从数据帧结构中获取所有信息:
df3.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29 entries, 104 to 132
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Zählung in 28 non-null object
1 Unnamed: 17 29 non-null object
2 Unnamed: 18 29 non-null object
3 Unnamed: 19 29 non-null object
4 Unnamed: 20 29 non-null object
5 Unnamed: 21 29 non-null object
6 Unnamed: 40 29 non-null object
7 Unnamed: 41 29 non-null object
8 Unnamed: 42 29 non-null object
9 Unnamed: 43 28 non-null object
10 Unnamed: 44 28 non-null object
11 Unnamed: 63 29 non-null object
12 Unnamed: 64 29 non-null object
13 Unnamed: 65 29 non-null object
14 Unnamed: 66 28 non-null object
dtypes: object(15)
memory usage: 3.5+ KB
这些列需要按其索引重命名,因此我创建一个字典,其中索引作为键,新名称作为值:
col_names= {0:'Zeit',
1:'ZU_PKW',
2: 'ZU_LKW1',
3: 'ZU_LKW2',
4: 'ZU_SV',
5: 'ZU_SV%',
6:'AB_PKW',
7: 'AB_LKW1',
8: 'AB_LKW2',
9: 'AB_SV',
10: 'AB_SV%',
11:'ALL_PKW',
12: 'ALL_LKW1',
13: 'ALL_LKW2',
14: 'ALL_SV'
}
我尝试使用“重命名”功能重命名包含所有选项的列:
inplace=True
df4 = df3.rename(index=col_names)
结果:没有错误,但列未重命名
inplace=True
df4 = df3.rename(index={col_names, inplace = True)
结果:错误:
A value is trying to be set on a copy of a slice from a DataFrame
结果 df 为 None
。
inplace=True
df3.rename(index={col_names, inplace = True)
结果:`错误:
A value is trying to be set on a copy of a slice from a DataFrame
并且 df3 保持不变。
axis=1
df3.rename(index={col_names, inplace = True)
退货
TypeError: Cannot specify both 'axis' and any of 'index' or 'columns'
我觉得我已经没有选择了。我做错了什么?难道和在jupyter Notebook环境下工作有关系吗?
如果需要按列索引重命名:
df.columns = [col_names.get(i) for i in range(len(df.columns))]