2016-04-19 37 views
2

我有一个数据帧像这样在物品栏:替换基于列表

Date  Value 
19990506 0.6 
19990506 0.8 
19990607 1.2 
20000802 0.4 

我也有两个列表如下:

list1 = ['19990506', '19990607', '20000802'] 
list2 = ['1999201', '1999232', '2000252'] 

list1的项目与中值一致列Date,我想将它们替换为list2中的项目。所以在Date199905061999201代替,199906071999232代替。我想我需要拉我的名单来做这件事,但在此之后,我对最好的方式感到不知所措。我正在显示一个非常简化的数据框,因此仅仅使用.replace对我来说效率不高。我所需的输出是这样的:

Date  Value 
1999201 0.6 
1999201 0.8 
1999232 1.2 
2000252 0.4 

回答

4

如果您创建一个映射,从list1list2字典那么你可以使用Series.map

df = pd.read_clipboard() 

list1 = ['19990506', '19990607', '20000802'] 
list2 = ['1999201', '1999232', '2000252'] 

# When I read in your data I get ints in the Date column 
# so I need ints in the replacement map, if you have 
# strings then remove the int() conversions 
replacement_map = {int(i1): int(i2) for i1, i2 in zip(list1, list2)} 
df['Date'] = df['Date'].map(replacement_map) 
df 
Out[13]: 
     Date Value 
0 1999201 0.6 
1 1999201 0.8 
2 1999232 1.2 
3 2000252 0.4