Pandas - AttributeError: 'DataFrame' 对象没有属性 'map'

新手上路,请多包涵

我正在尝试通过基于现有列创建字典并在列上调用“映射”函数来在数据框中创建一个新列。它似乎工作了很长一段时间。然而,笔记本开始抛出

AttributeError: ‘DataFrame’ 对象没有属性 ‘map’

我没有更改内核或 python 版本。这是我正在使用的代码。

 dict= {1:A,
       2:B,
       3:C,
       4:D,
       5:E}

# Creating an interval-type
data['new'] = data['old'].map(dict)

如何解决这个问题?

原文由 redwolf_cr7 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

Main problem is after selecting old column get DataFrame instead Series , so map implemented yet to Series failed.

这里应该是重复的列 old ,所以如果选择一列它返回所有列 oldDataFrame

 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]])

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

map 是一种可以在 pandas.Series 对象上调用的方法。 pandas.DataFrame 对象上不存在此方法。

 df['new'] = df['old'].map(d)

在您的代码中 ^^^ df[‘old’] 由于某种原因返回了一个 pandas.Dataframe 对象。

  • 正如@jezrael 指出的那样,这可能是由于数据框中有多 个旧 列。

  • 或者您的代码可能与您给出的示例不完全相同。

  • 无论哪种方式,错误都存在,因为您在 pandas.Dataframe 对象上调用 map()

原文由 Arran Duff 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进