2017-02-20 41 views
1

如何將1 ns填充到Pandas DataFrame中所有重複的DatetimeIndex如何將1 ns填充到Pandas DataFrame中所有重複的DatetimeIndex?

例如,從這個:

2016-11-13 20:00:10.617989120 
2016-11-13 20:00:10.617989120 
2016-11-13 20:00:10.617989120 
2016-11-13 20:00:10.123945353 
2016-11-13 20:00:14.565989314 
2016-11-13 20:00:18.565989315 
2016-11-13 20:00:18.565989315 
2016-11-13 20:00:18.565989315 

這樣:

2016-11-13 20:00:10.617989120 
2016-11-13 20:00:10.617989121 
2016-11-13 20:00:10.617989122 
2016-11-13 20:00:10.123945353 
2016-11-13 20:00:14.565989314 
2016-11-13 20:00:18.565989315 
2016-11-13 20:00:18.565989316 
2016-11-13 20:00:18.565989317 

回答

0

您可以使用cumcount與轉換to_timedelta

print (df.groupby(level=0).cumcount()) 
2016-11-13 20:00:10.617989120 0 
2016-11-13 20:00:10.617989120 1 
2016-11-13 20:00:10.617989120 2 
2016-11-13 20:00:10.123945353 0 
2016-11-13 20:00:14.565989314 0 
2016-11-13 20:00:18.565989315 0 
2016-11-13 20:00:18.565989315 1 
2016-11-13 20:00:18.565989315 2 
dtype: int64 

df.index = df.index + pd.to_timedelta(df.groupby(level=0).cumcount()) 
print (df.index) 
DatetimeIndex(['2016-11-13 20:00:10.617989120', 
       '2016-11-13 20:00:10.617989121', 
       '2016-11-13 20:00:10.617989122', 
       '2016-11-13 20:00:10.123945353', 
       '2016-11-13 20:00:14.565989314', 
       '2016-11-13 20:00:18.565989315', 
       '2016-11-13 20:00:18.565989316', 
       '2016-11-13 20:00:18.565989317'], 
       dtype='datetime64[ns]', freq=None) 
+0

改編我使用cumsum,試圖讓同樣的結果,它當然不工作..我不知道cumcount()謝謝! –

相關問題