KeyError: 0 when accessing value in pandas series

问题描述 投票:0回答:3

在我的脚本中,我有 df['Time'] 如下所示。

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]

但是当我做

t1=pd.Timestamp(df['Time'][0])

我收到这样的错误:

按键错误:0

我需要在这里进行任何类型转换吗?如果是,那么如何修复它?

python pandas indexing series keyerror
3个回答
42
投票

你在找

df.iloc
.

df['Time'].iloc[0]

df['Time'][0]
如果你的系列有一个从
0

开始的索引会有效

如果需要标量只使用

Series.iat

df['Time'].iat[0]

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, :], 

0
投票

问题

就我而言,因为我删除了第一行(包含索引标题):

df.iloc[1:]

传递

0
的索引会失败:

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

解决方案

将此添加到您正在索引/切片的数据框的末尾:

df.reset_index(drop=True)
© www.soinside.com 2019 - 2024. All rights reserved.