【发布时间】: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