什么是pandas数据帧中标识的系列对象



我写道:

import pandas as pd

df_name=pd.DataFrame({'CODE':['01','02','03','04'],
'NAME':['MICK','DAVID','JEAN','CHERRY']})
df_exp=pd.DataFrame({'TEST':['POST1','POST2','POST3','POST4','POST5','POST6','POST7', 'POST8'],
'PERS CODE':['02','03','01','04','01','02','02','03']})
print(df_name)
print(df_exp)
df_output=pd.DataFrame()
df_output['POST']=df_exp['TEST']
df_output['AGENT']=df_name['NAME'].where(df_name['CODE']==df_exp['PERS CODE'])
print (df_output)

它返回一条错误消息:ValueError:只能比较标记相同的Series对象我不明白为什么。。。

这意味着您的两个系列具有不同的索引,并且无法与==进行比较(如果索引大小相同,则这将起作用(。

改为使用eq

df_name['CODE'].eq(df_exp['PERS CODE'])

上下文:

df_output['AGENT'] = df_name['NAME'].where(df_name['CODE'].eq(df_exp['PERS CODE']))

输出:

POST   AGENT
0  POST1     NaN
1  POST2     NaN
2  POST3     NaN
3  POST4  CHERRY  # in order of the Series indices, only POST4 matches
4  POST5     NaN
5  POST6     NaN
6  POST7     NaN
7  POST8     NaN

然而,我怀疑这不是你想要的,我更希望map的名称:

df_output['AGENT'] = df_exp['PERS CODE'].map(df_name.set_index('CODE')['NAME'])

输出:

POST   AGENT
0  POST1   DAVID
1  POST2    JEAN
2  POST3    MICK
3  POST4  CHERRY
4  POST5    MICK
5  POST6   DAVID
6  POST7   DAVID
7  POST8    JEAN