In my script I have df['Time'] as shown below.
497 2017-08-06 11:00:00
548 2017-08-08 15:00:00
580 2017-08-10 04:00:00
646 2017-08-12 23:00:00
Name: Time, dtype: datetime64[ns]
But when i do
t1=pd.Timestamp(df['Time'][0])
I get an error like this :
KeyError: 0
Do I need any type conversion here, if yes then how it can be fixed?
We can simply fix the error by correcting the spelling of the key. If we are not sure about the spelling we can simply print the list of all column names and crosscheck.
The Python "KeyError: 0" exception is caused when we try to access a 0 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.
The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.
Pandas KeyError. In most cases, think of 'key' as the same as 'name.' Pandas is telling you that it can not find your column name. The preferred method is to *make sure your column name is in your dataframe.*
Accessing elements of a Pandas Series. Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). Labels need not be unique but must be a hashable type. An element in the series can be accessed similarly to that in an ndarray.
This error occurs when you attempt to access some column in a pandas DataFrame that does not exist. Typically this error occurs when you simply misspell a column names or include an accidental space before or after the column name. The following example shows how to fix this error in practice.
What a Python KeyError Usually Means A Python KeyError exception is what is raised when you try to access a key that isn’t in a dictionary (dict). Python’s official documentation says that the KeyError is raised when a mapping key is accessed and isn’t found in the mapping. A mapping is a data structure that maps one set of values to another.
Since there is no ‘point’ column in our DataFrame, we receive a KeyError. The way to fix this error is to simply make sure we spell the column name correctly.
You're looking for df.iloc
.
df['Time'].iloc[0]
df['Time'][0]
would've worked if your series had an index beginning from 0
And if need scalar only use Series.iat
:
df['Time'].iat[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With