主要问题是在选择old 列后得到DataFrame 而不是Series,所以map 实现尚未Series 失败。
这里应该重复列old,所以如果选择一列,它将返回DataFrame中的所有列old:
df = pd.DataFrame([[1,3,8],[4,5,3]], columns=['old','old','col'])
print (df)
old old col
0 1 3 8
1 4 5 3
print(df['old'])
old old
0 1 3
1 4 5
#dont use dict like variable, because python reserved word
df['new'] = df['old'].map(d)
print (df)
AttributeError: 'DataFrame' 对象没有属性 'map'
重复删除此列的可能解决方案:
s = df.columns.to_series()
new = s.groupby(s).cumcount().astype(str).radd('_').replace('_0','')
df.columns += new
print (df)
old old_1 col
0 1 3 8
1 4 5 3
另一个问题应该是MultiIndex列,测试:
mux = pd.MultiIndex.from_arrays([['old','old','col'],['a','b','c']])
df = pd.DataFrame([[1,3,8],[4,5,3]], columns=mux)
print (df)
old col
a b c
0 1 3 8
1 4 5 3
print (df.columns)
MultiIndex(levels=[['col', 'old'], ['a', 'b', 'c']],
codes=[[1, 1, 0], [0, 1, 2]])
并且解决方案是扁平化MultiIndex:
#python 3.6+
df.columns = [f'{a}_{b}' for a, b in df.columns]
#puthon bellow
#df.columns = ['{}_{}'.format(a,b) for a, b in df.columns]
print (df)
old_a old_b col_c
0 1 3 8
1 4 5 3
另一种解决方案是使用元组映射MultiIndex 并分配给新的tuple:
df[('new', 'd')] = df[('old', 'a')].map(d)
print (df)
old col new
a b c d
0 1 3 8 A
1 4 5 3 D
print (df.columns)
MultiIndex(levels=[['col', 'old', 'new'], ['a', 'b', 'c', 'd']],
codes=[[1, 1, 0, 2], [0, 1, 2, 3]])