2016-12-04 59 views
0

我有一个数据帧(DF1)等,所以当“字典”对象不是可调用:类型错误:使用替换映射

Date  Value 
19920507 1.02 
19930602 1.11 
19980802 6.07 

,我想基于第二数据帧(DF2),它是像重新映射Date这样的:

Date1   Date2 
19920507  1 
19930602  2 
19980802  3 

我在第一个数据帧替换Date像这样:

list_1=df2.Date1.tolist() 
list_2=df.Date2.tolist() 
replacement_map = {int(i1): int(i2) for i1, i2 in zip(list_1, list_2)} 

df['Date'] = df['Date'].apply(replacement_map) 

但这返回:

File "C:\Users\Stefano\Anaconda2_2\lib\site-packages\pandas\core\series.py", line 2220, in apply 
    mapped = lib.map_infer(values, f, convert=convert_dtype) 

    File "pandas\src\inference.pyx", line 1088, in pandas.lib.map_infer (pandas\lib.c:62658) 

TypeError: 'dict' object is not callable 

回答

1

“不可调用”基本上意味着它不是一个功能,Series.apply接受功能 - 没有字典。

尝试map代替:

df['Date'] = df['Date'].map(replacement_map) 

注意:要使用map,你不必你的映射转换成字典。一系列其索引的键,其值是字典值会做的一样好:

df1['Date'] = df1['Date'].map(df2.set_index('Date1')['Date2']) 

df1 
Out: 
    Date Value 
0  1 1.02 
1  2 1.11 
2  3 6.07 

当然,这些都是可能的merge & join为好。

+1

我真的很享受我可以跳过字典步骤,谢谢你的建议 –