2013-06-12 29 views
0

我試圖將熊貓數據框中的索引轉換爲日期時間對象,以便我可以選擇時間範圍。對熊貓的索引對象進行操作

假設my_df是我一起工作的數據幀,我有以下幾點:

# Conversion function: 
def convert_times(x): return datetime.strptime(x, '%H:%M:%S.%f') 

# Convert every index value in my dataframe 
my_df.index = map(convert_times, my_df.index) 

,但我注意到,

map(convert_times, my_df.index) 

返回一個列表,所以上面的代碼轉換的指數到一個列表,該列表被轉換回索引。

有沒有辦法直接對索引對象進行操作?

+1

你真的沒有年/月/日嗎?這些日期肯定是垃圾(1900年)? –

+0

謝謝@Andy,恐怕我不知道,但是,是的,你說得對,我得到了1900-1-1。 –

+0

你期望什麼(他們是什麼意思)......? –

回答

2

我會to_datetime直接使用:

datetime_format = '%H:%M:%S.%f' # tweak depending on format of dates 

df.index = pd.to_datetime(df.index, format=format_datetime) 

這將是比使用地圖(尤其是Python的內置地圖)更快大大

注意:to_datetime不需要format參數。