28

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?

Tms91
  • 3,456
  • 6
  • 40
  • 74
Bharat Sharma
  • 1,081
  • 3
  • 11
  • 23
  • 1
    Try `df['Time'].iloc[0]`. Since `0` doesn't exist in index it doesn't work. For positional indexing you need to use `.iloc` – Zero Sep 11 '17 at 10:37

3 Answers3

44

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
cs95
  • 379,657
  • 97
  • 704
  • 746
0
def get_time_slice(full_matrix, start = 0., period = 1.):
    """
    Returns a slice of the given matrix, where start is the offset and period is 
    used to specify the length of the signal.
    
    Parameters:
        full_matrix (numpy.ndarray): matrix returned by matrix_from_csv()
        start (float): start point (in seconds after the beginning of records) 
        period (float): duration of the slice to be extracted (in seconds)
    Returns:
        numpy.ndarray: 2D matrix with the desired slice of the matrix
        float: actual length of the resulting time slice
        
    Author:
        Original: [lmanso]
        
I have also error clear to me anyone
Reimplemented: [fcampelo]
    """
    
    # Changed for greater efficiency [fcampelo]
    rstart  = full_matrix[0: 0] + start
    index_0 = np.max(np.where(full_matrix[: 0] <= rstart))
    index_1 = np.max(np.where(full_matrix[: 0] <= rstart + period))
    
    duration = full_matrix[index_1, 0] - full_matrix[index_0, 0]
    return full_matrix[index_0:index_1, :], 
  • I Have also error in this same problem anyone solve me – Dhivya Bharkavi Jan 12 '23 at 05:00
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 12 '23 at 16:40
0

Problem

In my case, since I had dropped the first row (which contained indexed headers):

df.iloc[1:]

Passing an index of 0 would fail:

df.iloc[0]
>>> KeyError: 0

Solution

Add this to the end of the Dataframe you are indexing / slicing:

df.reset_index(drop=True)
DanielBell99
  • 896
  • 5
  • 25
  • 57