1

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'
1
  • 1
    You have datetime objects in a pd.Index index, so you have to access the index with datetime - df.loc[datetime.date(1992,3,1)]. You could use strings directly if you had pd.DatetimeIndex Commented Oct 7, 2019 at 13:42

1 Answer 1

2

Create DatetimeIndex with to_datetime for convert dates objects to timestamps:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.