【问题标题】:Keyerror in time/Date Components of datetime - what to do?日期时间的时间/日期组件中的键错误 - 怎么办?
【发布时间】:2019-09-22 07:28:10
【问题描述】:

我正在使用带有日期时间索引的 pandas DataFrame。我知道从 Xarray documentation,日期时间索引可以作为ds['date.year'] 完成,其中 ds 是 xarray 的 DataArray,date 是日期索引和日期的年份。 Xarray 指向datetime components ,这又指向DateTimeIndex,后者是熊猫文档。所以我想对 pandas 做同样的事情,因为我真的很喜欢这个功能。

但是,它对我不起作用。这是我到目前为止所做的:

# Import required modules
import pandas as pd
import numpy as np

# Create DataFrame (name: df)
df=pd.DataFrame({'Date': ['2017-04-01','2017-04-01',
                          '2017-04-02','2017-04-02'],
                 'Time': ['06:00:00','18:00:00',
                          '06:00:00','18:00:00'],
                 'Active': [True,False,False,True],
                 'Value': np.random.rand(4)})

# Combine str() information of Date and Time and format to datetime
df['Date']=pd.to_datetime(df['Date'] + ' ' + df['Time'],format = '%Y-%m-%d %H:%M:%S')

# Make the combined data the index
df = df.set_index(df['Date'])

# Erase the rest, as it is not required anymore
df = df.drop(['Time','Date'], axis=1)

# Show me the first day
df['2017-04-01']

好的,所以这只会显示第一个条目。到目前为止,一切都很好。 不过

df['Date.year']

结果为@​​987654327@

我希望输出像

array([2017,2017,2017,2017])

我做错了什么?


编辑:


我有一个解决方法,我可以继续使用,但我仍然不满意,因为这不能解释我的问题。我没有使用 pandas DataFrame,而是使用 xarray 数据集,现在可以使用:

# Load modules
import pandas as pd
import numpy as np
import xarray as xr

# Prepare time array
Date = ['2017-04-01','2017-04-01', '2017-04-02','2017-04-02']
Time = ['06:00:00','18:00:00', '06:00:00','18:00:00']
time = [Date[i] + ' ' + Time[i] for i in range(len(Date))]
time = pd.to_datetime(time,format = '%Y-%m-%d %H:%M:%S')

# Create Dataset (name: ds)
ds=xr.Dataset({'time': time,
               'Active': [True,False,False,True],
               'Value': np.random.rand(4)})

ds['time.year']

给出:

<xarray.DataArray 'year' (time: 4)>
array([2017, 2017, 2017, 2017])
Coordinates:
  * time     (time) datetime64[ns] 2017-04-01T06:00:00 ... 2017-04-02T18:00:00

【问题讨论】:

  • 试试list(df['Date'].dt.year)这将返回一个年份数组。
  • 哦,因为你的日期是你的索引(抱歉错过了)试试df.index.year

标签: python-3.x pandas datetime python-xarray


【解决方案1】:

就你做错了什么而言,你是

a) 尝试将索引称为系列 b) 在字符串 df['Date'] 中更改命令是单列 df['Date.year'] 是名为 'Date.year' 的列

如果您的日期时间是索引,则使用 .yeardt.year 如果它是一个系列。

df.index.year 
#or assuming your dtype is a proper datetime (your code indicates it is)
df.Date.dt.year

希望对萌芽有所帮助。

【讨论】:

  • 嗨@datanovice。 感谢您的快速回答,非常感谢! df.index.year 将产生 Int64Index([2017, 2017, 2017, 2017], dtype='int64', name='Date')df.Date.dt.year 产生 AttributeError: 'DataFrame' object has no attribute 'Date'。然而,这一切仍然不是我想要的!请查看 xarray 文档。请观看我的编辑。
  • 嘿加布里埃尔,抱歉我没有使用 xarray 快速浏览他们的文档的经验,看起来您需要将数据框传递给 xarray,我看不到您在代码中这样做?
  • 嗨@datanovice。不,它与 xarray 一起工作,就像我更新我的 OP 一样。现在的问题是,如果同样适用于熊猫。我以为是这样,但现在我不确定了:) 无论如何,感谢您再次回到这里并提供帮助!
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 2016-09-16
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
相关资源
最近更新 更多