Reputation: 808
I'm using Pandas to process List data. The list data is
[(datetime.date(1992, 2, 1), 114535.0), (datetime.date(1992, 3, 1), 120025.0), (datetime.date(1992, 4, 1), 124470.0), (datetime.date(1992, 5, 1), 125822.0), (datetime.date(1992, 6, 1), 122834.0)]
I create labels and use DataFrame.from_records to read the data
labels = ['date', 'value']
df = pd.DataFrame.from_records(listData, columns=labels)
df = df.set_index('date')
print(df.loc['1992-03-01'])
I got the following error using df.loc
File "/usr/lib64/python3.6/site-packages/pandas/core/indexes/base.py", line 2890, in get_loc
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '1992-03-01'
Upvotes: 1
Views: 335
Reputation: 863801
Create DatetimeIndex
with to_datetime
for convert dates objects
to timestamp
s:
labels = ['date', 'value']
df = pd.DataFrame.from_records(listData, columns=labels)
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
print(df.loc['1992-03-01'])
value 120025.0
Name: 1992-03-01 00:00:00, dtype: float64
Or looking by date objects:
labels = ['date', 'value']
df = pd.DataFrame.from_records(listData, columns=labels)
df = df.set_index('date')
print(df.loc[datetime.date(1992, 3, 1)])
value 120025.0
Name: 1992-03-01, dtype: float64
Upvotes: 2