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

巨蟒熊猫:地图和返回南

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

    我有两个数据帧,第一个是:

    id code
    1   2
    2   3
    3   3
    4   1
    

    第二个是:

    id code  name
    1    1   Mary
    2    2   Ben
    3    3   John
    

    我想映射数据帧1,使其看起来像:

    id code  name
    1   2    Ben
    2   3    John
    3   3    John
    4   1    Mary
    

    我尝试使用此代码:

    mapping = dict(df2[['code','name']].values)
    df1['name'] = df1['code'].map(mapping)
    

    我的映射是正确的,但映射值都是NaN:

    mapping = {1:"Mary", 2:"Ben", 3:"John"}
    
    id code  name
    1   2    NaN
    2   3    NaN
    3   3    NaN
    4   1    NaN
    

    有人知道为什么要解决吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   jezrael    7 年前

    问题是列中的值类型不同 code 所以有必要转换成整数或字符串 astype 对于两种类型中的相同类型:

    print (df1['code'].dtype)
    object
    
    print (df2['code'].dtype)
    int64
    
    print (type(df1.loc[0, 'code']))
    <class 'str'>
    
    print (type(df2.loc[0, 'code']))
    <class 'numpy.int64'>
    

    mapping = dict(df2[['code','name']].values)
    #same dtypes - integers
    df1['name'] = df1['code'].astype(int).map(mapping)
    
    #same dtypes - object (obviously strings)
    df2['code'] = df2['code'].astype(str)
    mapping = dict(df2[['code','name']].values)
    df1['name'] = df1['code'].map(mapping)
    

    print (df1)
       id code  name
    0   1    2   Ben
    1   2    3  John
    2   3    3  John
    3   4    1  Mary
    
        2
  •  2
  •   Sociopath    7 年前

    另一种方法是使用 dataframe.merge

    df.merge(df2.drop(['id'],1), how='left', on=['code'])
    

    输出:

        id  code   name
    0   1   2      Ben
    1   2   3      John
    2   3   3      John
    3   4   1      Mery