无法按d分析pandas中的索引

2024-10-16 17:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读了好几篇文章,但无法解决这个问题,我有一个数据帧,跨越几个星期

2018-10-25 16:00:03.003 tag1   6
2018-10-25 16:00:03.003 tag2   10
2018-10-25 16:00:03.003 tag3   11
2018-10-25 16:00:03.003 tag4   12
2018-10-25 16:00:03.003 tag5   9
....

它是用

df = pd.concat([pd.read_csv(f,names=['time','tag','value'],index_col=0,parse_dates=True) for f in glob.glob(path)],
                   sort=False)

当我尝试用df.loc['2018-10-25']按索引返回一天时,它返回KeyError: u'the label['2018-10-25']不在[索引]中

用这种方法一天怎么提取 输出df.index()is TypeError: Index is not callable ?

在@ALollz建议中,删除parsedates并执行以下操作:

df['time'] = pd.to_datetime(df['time'],errors='coerce')
df.set_index('time',inplace=True)

返回KeyError: time


Tags: 数据truedfindextimeis文章glob
1条回答
网友
1楼 · 发布于 2024-10-16 17:28:23

问题是你的分离器。文件以空格分隔,但CSV默认为逗号(head slap)。结果,您的输入解析没有发现逗号,将整行保留为单个列的输入值。测向指数这清楚地表明:

Index(['2018-10-25 16:00:03.003 tag1   6', 
       '2018-10-25 16:00:03.003 tag2   10',
       '2018-10-25 16:00:03.003 tag3   11',
       '2018-10-25 16:00:03.003 tag4   12',
       '2018-10-25 16:00:03.003 tag5   9'],
      dtype='object', name='time')

因此,输入不会解析为日期,并且无法使用Pandas中的日期工具进行搜索。你知道吗

按照当前解析的预期,在数据集中插入逗号,或者指定空白作为文件分隔符。这将产生一个索引

DatetimeIndex(['2018-10-25 16:00:03.003000', '2018-10-25 16:00:03.003000',
               '2018-10-25 16:00:03.003000', '2018-10-25 16:00:03.003000',
               '2018-10-25 16:00:03.003000'],
              dtype='datetime64[ns]', name='time', freq=None)

。。。您的日期搜索命令会很好地返回:

                           tag  value
time                                 
2018-10-25 16:00:03.003   tag1      6
2018-10-25 16:00:03.003   tag2     10
2018-10-25 16:00:03.003   tag3     11
2018-10-25 16:00:03.003   tag4     12
2018-10-25 16:00:03.003   tag5      9

相关问题 更多 >