我有Pandas DataFrame(從.csv加載),日期時間作爲索引..每天有/必須有一個條目。 問題是我有空隙,即有幾天我根本沒有數據。 插入行(天)的最簡單方法是什麼?還有一種方法可以控制將數據插入列中作爲數據!說0或複製prev day info或填充從prev-date到next-date數據值範圍內的滑動增加/減少值。熊貓數據框的填充日期間隙
感謝
我這裏是01-03和01-04缺失:
In [60]: df['2015-01-06':'2015-01-01']
Out[60]:
Rate High (est) Low (est)
Date
2015-01-06 1.19643 0.0000 0.0000
2015-01-05 1.20368 1.2186 1.1889
2015-01-02 1.21163 1.2254 1.1980
2015-01-01 1.21469 1.2282 1.2014
尚在測試階段,但是這似乎是解決問題:
df.set_index(pd.DatetimeIndex(df.Date),inplace=True)
和然後重新採樣...原因是導入帶有header-col-name Date的.csv實際上並不是創建日期時間索引,但凍結列表無論如何。 重採樣()期待:如果isinstance(斧,DatetimeIndex):.....
這是我最終的解決方案:
#make dates the index
self.df.set_index(pd.DatetimeIndex(self.df.Date), inplace=True)
#fill the gaps
self.df = self.df.resample('D',fill_method='pad')
#fix the Date column
self.df.Date = self.df.index.values
我不得不修復的日期列,因爲重採樣()只是讓你去填充它。 雖然它修正了索引,所以我可以用它來修復日期列。
在這裏被修正後剪斷的數據的:
2015-01-29 2015-01-29 1.13262 0.0000 0.0000
2015-01-30 2015-01-30 1.13161 1.1450 1.1184
2015-01-31 2015-01-31 1.13161 1.1450 1.1184
2015-02-01 2015-02-01 1.13161 1.1450 1.1184
01-30,01-31是新生成的數據。
df.index應該是'DatetimeIndex',我推薦使用'pd.to_datetime'而不是pd.DatetimeIndex構造函數。 'df.index.names'是「索引標題」(列標記,例如「Rate」,索引的級別也是如此)。 – 2015-02-12 01:41:12
我可以在cvs導入時做到這一點(pd.read_csv()) – user1019129 2015-02-12 02:35:52
是的,'parse_dates = True'可以做到這一點。 – 2015-02-12 05:45:13