2016-09-30 139 views
3

我有以下的數據幀df索引的日期時間大熊貓據幀失敗

      Candy  Apple  Banana 
2016-09-14 19:00:00 109.202060 121.194138 130.372082 
2016-09-14 20:00:00 109.199083 121.188817 130.380736 
2016-09-14 21:00:00 109.198894 121.180553 130.366054 
2016-09-14 22:00:00 109.192076 121.148722 130.307342 
2016-09-14 23:00:00 109.184374 121.131068 130.276691 
2016-09-15 00:00:00 109.191582 121.159304 130.316872 
2016-09-15 01:00:00 109.183895 121.133062 130.269966 
2016-09-15 02:00:00 109.193550 121.174708 130.337563 
2016-09-15 03:00:00 109.196597 121.153076 130.274463 
2016-09-15 04:00:00 109.195608 121.168936 130.276042 
2016-09-15 05:00:00 109.211957 121.208946 130.330430 
2016-09-15 06:00:00 109.210598 121.214454 130.365404 
2016-09-15 07:00:00 109.224667 121.285534 130.508604 
2016-09-15 08:00:00 109.220784 121.248828 130.389024 
2016-09-15 09:00:00 109.199448 121.155439 130.212834 
2016-09-15 10:00:00 109.226648 121.276439 130.427642 
2016-09-15 11:00:00 109.239957 121.311719 130.462447 

我想從過去的6時段創造出只有數據的第二數據幀。

df.index = pd.to_datetime(df.index,infer_datetime_format=True) 

last_row = df.tail(1).index 

six_hour = last_row - timedelta(hours=6) 

df_6hr = df.loc[six_hour:last_row] 
print df_6hr 

我得到以下錯誤:

File "pandas/tslib.pyx", line 298, in pandas.tslib.Timestamp.new (pandas/tslib.c:9013)
File "pandas/tslib.pyx", line 1330, in pandas.tslib.convert_to_tsobject (pandas/tslib.c:25826)

TypeError: Cannot convert input to Timestamp

怎麼就不行?

回答

2

你需要添加[0],因爲你需要選擇列表中的第一項:

last_row = df.tail(1).index[0] 
print (last_row) 
2016-09-15 11:00:00 

last_row = df.tail(1).index 
print (last_row) 
DatetimeIndex(['2016-09-15 11:00:00'], dtype='datetime64[ns]', freq=None) 

更好的解決方案是簡單的[-1]選擇指數的最後一個值:

last_row = df.index[-1] 
print (last_row) 
2016-09-15 11:00:00 
+0

謝謝那工作...我要如何添加[0]?輸出是不是隻有一排? – A1122

+0

oooh,謝謝! – A1122

+0

很高興能爲您提供幫助! – jezrael