代码之家  ›  专栏  ›  技术社区  ›  redwolf_cr7

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

  •  2
  • redwolf_cr7  · 技术社区  · 7 年前

    我试图在数据框中创建一个新列,方法是基于现有列创建一个字典,并对该列调用“map”函数。它似乎工作了相当长的一段时间。然而,笔记本开始乱扔

    AttributeError:“DataFrame”对象没有属性“map”

    dict= {1:A,
           2:B,
           3:C,
           4:D,
           5:E}
    
    # Creating an interval-type 
    data['new'] = data['old'].map(dict)
    

    如何解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Arran Duff    7 年前

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

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

    在代码中^^^ df['old'] 由于某种原因正在返回pandas.Dataframe对象。

    • 古老的 数据帧中的列。
    • 或者,您的代码可能与您给出的示例不完全相同。

    • 无论哪种方式,错误都存在,因为您正在呼叫 地图() 在pandas.Dataframe对象上

        2
  •  1
  •   jezrael    7 年前

    主要问题是在选择之后 old 列获取 DataFrame Series 所以 map 尚未实施 系列 失败。

    这里应该是重复的列 古老的 ,因此,如果选择一列,它将返回所有列 在里面 数据帧

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

    解决方案是扁平化 :

    #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
    

    另一个解决方案是映射方式 使用tuple并分配给new 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]])
    
        3
  •  0
  •   chutian    5 年前
    import pandas as pd
    f_dict = {1:0,2:1,3:2}
    m = pd.Series([1,2,3])
    res = m.map(f_dict)
    print(res)
    

    import pandas as pd
    f_dict = {1:0,2:1,3:2}
    m = pd.DataFrame([1,2,3])
    res = m.map(f_dict)
    print(res)