当访问Pandas系列中的值时,出现KeyError: 0。

28

在我的脚本中,我有如下所示的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])

我收到了这样一个错误:

KeyError: 0

这里需要进行任何类型的转换吗?如果需要,那么应该如何解决?


1
尝试使用 df['Time'].iloc[0]。由于索引中不存在 0,所以它无法工作。要进行位置索引,您需要使用 .iloc - Zero
3个回答

44

你需要使用 df.iloc

df['Time'].iloc[0]

如果您的序列从0开始索引,那么df ['Time'] [0]将起作用。

如果只需要标量,请使用Series.iat

df['Time'].iat[0]

3
既然 dtypedatetime ,那么 to_datetimepd.Timestamp 就不是必需的。 - Bharath M Shetty

0

问题

在我的情况下,由于我已经删除了第一行(其中包含索引标题):

df.iloc[1:]

传递索引0将失败:

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

解决方案

将此代码添加到您正在索引/切片的Dataframe的结尾即可:

df.reset_index(drop=True)

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

我在同一个问题上也遇到了错误,有人能帮我解决吗? - Dhivya Bharkavi
1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接