2016-04-19 39 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