当前位置: 首页 > 知识库问答 >
问题:

python键错误:“日期时间”

薛承基
2023-03-14

我有一个熊猫的数据帧

pd1 = pd.read_csv(r'c:\am\wiki_stats\topandas.txt',sep=':',
                  header=None, names  = ['date-time','domain','requests-qty','response-bytes'],
                   parse_dates=[1], converters={'date-time': to_datetime}, index_col = 'date-time')

带索引

>> pd1.index:  

 DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 00:00:00',
                '2016-01-01 00:00:00', '2016-01-01 00:00:00',
                '2016-01-01 00:00:00', '2016-01-01 00:00:00',
                '2016-01-01 00:00:00', '2016-01-01 00:00:00',
                '2016-01-01 00:00:00', '2016-01-01 00:00:00',
                ...
                '2016-08-05 12:00:00', '2016-08-05 12:00:00',
                '2016-08-05 12:00:00', '2016-08-05 12:00:00',
                '2016-08-05 12:00:00', '2016-08-05 12:00:00',
                '2016-08-05 12:00:00', '2016-08-05 12:00:00',
                '2016-08-05 12:00:00', '2016-08-05 12:00:00'],
               dtype='datetime64[ns]', name='date-time', length=6084158, freq=None)

但当我想设置该列的索引时,我得到了如下错误(我最初想设置多列索引,出现了错误,然后试图从中创建其他数据pd_new_index=pd1.set_index(['requests-qty','domain']),其他列作为索引(ok)要创建新框架,请将索引设置为“日期-时间”列,返回pd\u new\u 2=pd\u new\u index.set\u index(['date-time'])-相同错误)“日期时间”看起来不像特殊的关键字,而且该列现在是索引。为什么会出错?

KeyErrorhtml" target="_blank">回溯(最近一次调用上次)C:\ProgramData\Anaconda3\lib\site packages\pandas\core\index\base。py in get_loc(自身、键、方法、公差)2656尝试:-

熊猫/_libs/索引。大熊猫中的pyx_图书馆。指数IndexEngine。获取_loc()

熊猫/_libs/索引。大熊猫中的pyx_图书馆。指数IndexEngine。获取_loc()

pandas/_libs/hashtable_class_helper。熊猫体内的pxi_图书馆。哈希表。PyObjectHashTable。获取_项()

pandas/_libs/hashtable_class_helper。熊猫体内的pxi_图书馆。哈希表。PyObjectHashTable。获取_项()

KeyError:“日期时间”

在处理上述异常期间,发生了另一个异常:

KeyError Traceback(最近的调用最后)在----

C:\ProgramData\Anaconda3\lib\site packages\pandas\core\frame。设置索引(self、key、drop、append、inplace、verify_integrity)4176个名称中的py。附加(无)4177其他:-

C:\ProgramData\Anaconda3\lib\site packages\pandas\core\frame。如果为self,则在getitem(self,key)2925中显示py。柱。N级

C:\Program Data\Anaconda3\lib\site-包\熊猫\core\索引\base.pyget_loc(自,键,方法,公差)2657
返回自。_engine.get_loc(键)2658除了KeyError:-

熊猫/_libs/索引。大熊猫中的pyx_图书馆。指数IndexEngine。获取_loc()

熊猫/_libs/索引。大熊猫中的pyx_图书馆。指数IndexEngine。获取_loc()

pandas/_libs/hashtable_class_helper。熊猫体内的pxi_图书馆。哈希表。PyObjectHashTable。获取_项()

pandas/_libs/hashtable_class_helper。熊猫体内的pxi_图书馆。哈希表。PyObjectHashTable。获取_项()

KeyError:“日期时间”

共有1个答案

柴嘉石
2023-03-14

原因是date-time已经是索引,这里DatetimeIndex,所以不能像按名称选择列一样选择它。

原因是参数index_col

pd1 = pd.read_csv(r'c:\am\wiki_stats\topandas.txt',
                  sep=':',
                  header=None, 
                  names  = ['date-time','domain','requests-qty','response-bytes'],
                  parse_dates=[1], 
                  converters={'date-time': to_datetime}, 
                  index_col = 'date-time')

对于MultiIndex,在index_col中添加列名列表,删除转换器并在parse_dates参数中指定列名:

import pandas as pd
from io import StringIO

temp=u"""2016-01-01:d1:0:0
2016-01-02:d2:0:1
2016-01-03:d3:1:0"""
#after testing replace 'pd.compat.StringIO(temp)' to r'c:\am\wiki_stats\topandas.txt''
df = pd.read_csv(StringIO(temp), 
                 sep=':',
                 header=None, 
                 names  = ['date-time','domain','requests-qty','response-bytes'],
                 parse_dates=['date-time'], 
                 index_col = ['date-time','domain'])

print (df)

date-time  domain                              
2016-01-01 d1                 0               0
2016-01-02 d2                 0               1
2016-01-03 d3                 1               0

print (df.index)
MultiIndex([('2016-01-01', 'd1'),
            ('2016-01-02', 'd2'),
            ('2016-01-03', 'd3')],
           names=['date-time', 'domain'])

EDIT1:在set\u index中使用append参数的解决方案

import pandas as pd
from io import StringIO


temp=u"""2016-01-01:d1:0:0
2016-01-02:d2:0:1
2016-01-03:d3:1:0"""
#after testing replace 'pd.compat.StringIO(temp)' to r'c:\am\wiki_stats\topandas.txt''
df = pd.read_csv(StringIO(temp), 
                 sep=':',
                 header=None, 
                 names  = ['date-time','domain','requests-qty','response-bytes'],
                 parse_dates=['date-time'], 
                 index_col = 'date-time')

print (df)
           domain  requests-qty  response-bytes
date-time                                      
2016-01-01     d1             0               0
2016-01-02     d2             0               1
2016-01-03     d3             1               0

print (df.index)
DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03'], 
              dtype='datetime64[ns]', name='date-time', freq=None)
df1 = df.set_index(['domain'], append = True)
print (df1)
                   requests-qty  response-bytes
date-time  domain                              
2016-01-01 d1                 0               0
2016-01-02 d2                 0               1
2016-01-03 d3                 1               0

print (df1.index)
MultiIndex([('2016-01-01', 'd1'),
            ('2016-01-02', 'd2'),
            ('2016-01-03', 'd3')],
           names=['date-time', 'domain'])
 类似资料:
  • 问题内容: 1. 当我在Windows上运行此MYSQL语法时,它正常运行: 但是,当我尝试在Linux上运行此代码时,出现错误: 2. 在Windows上,大小写不敏感。并且都被认为是相同的。但是在linux上,情况是敏感的。 Linux的配置: MySQL 5.5.33,phpMyAdmin:4.0.5,PHP:5.2.17 Windows的配置: MySql:5.6.11,phpMyAdmi

  • 问题内容: 我接收到来自Twitter的特定日期以特定格式发送的Twitter消息: 我想将这些日期存储在带有djangos DateTimeField字段的postgresql中的“带有时区的时间戳”字段中。但是,当我存储该字符串时,出现此错误: 我可以自动将twitter datetype转换为python datetime时间(在我的应用程序中的其他地方可以保存日期)。 问题答案: 编写这样

  • 我有以下应该返回时间戳的函数。当使用以下斜杠以字符串格式输入日期时,此代码有效:“2019/3/4”,但在使用 怎么回事?

  • 问题内容: 有一些与此相关的帖子,但是我对TSQL还是很陌生,无法理解它们,所以请原谅。 我的程序有: 如果我以这种方式执行它: 我收到此错误:从字符串转换日期时间时转换失败。 我该如何解决? 太感谢了 问题答案: 如果您查看CONVERT的文档,则会看到格式102是ANSI格式,即。因此,通过类似的日期应该可以。 它看起来也可以使用,但这不在文档格式中。

  • 我正在以字符串格式从Firestore获取日期,然后我正在转换日期时间,但日期时间.parse()给我错误的日期 实际日期为(yyyy-MM-dd HH: mm)=2022-01-29 15:23输出为(yyyy-MM-dd HH: mm)=2024-05-01 15:23 你能解释一下为什么它是给予的吗?

  • 问题内容: 谁能通过示例JSP代码帮助我,以通过JDBC在MySql数据库中存储日期?当我尝试执行下面给出的代码时,出现以下异常: com.mysql.jdbc.MysqlDataTruncation:数据截断:不正确的datetime值:第1行的’date’列的’‘ 如何克服这个问题?以下是我的代码: 问题答案: 要将日期设置为准备好的语句,您需要更改值的类型: 现在将String date转换