Reputation: 41
poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.set_index(poorList)
then it was Error:
File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4066) File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930) File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408) File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359) KeyError: datetime.date(2016, 5, 2)
Please tell me how to do it ?
Upvotes: 4
Views: 1641
Reputation: 29711
To generate an index with time stamps, you can use either the DatetimeIndex
or Index constructor and pass in a list of datetime objects:
dateForm.set_index(pd.DatetimeIndex(poorList), inplace=True) # Even pd.Index() works
Another way of doing would be to convert the list into an array as set_index
accepts it's key as arrays and specify it's dtype accordingly.
dateForm.set_index(np.array(poorList, dtype='datetime64'), inplace=True)
Upvotes: 0
Reputation: 862406
Another solutions is assign list converted to_datetime
or DatetimeIndex
:
poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.index = pd.DatetimeIndex(poorList)
print (dateForm.index)
DatetimeIndex(['2016-05-02', '2016-08-26', '2016-06-09', '2016-03-04'],
dtype='datetime64[ns]', freq=None)
Solution with sample:
dateForm = pd.DataFrame({'A':[1,2,3,7],
'B':[4,5,6,8]})
print (dateForm)
A B
0 1 4
1 2 5
2 3 6
3 7 8
poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.index = pd.to_datetime(poorList)
print (dateForm)
A B
2016-05-02 1 4
2016-08-26 2 5
2016-06-09 3 6
2016-03-04 7 8
print (dateForm.index)
DatetimeIndex(['2016-05-02', '2016-08-26', '2016-06-09', '2016-03-04'],
dtype='datetime64[ns]', freq=None)
Upvotes: 2
Reputation: 103
DataFrame.set_index() expects a column name or list of columns as an argument, so you should do:
dateForm['date'] = poorList
dateForm.set_index('date', inplace=True)
Upvotes: 1