创建和更改为Datetime、DatetimeIndex,时间序列

创建DatetimeIndex

1. pd.date_range(start= '2018-05-01', end= '2018-12-31')
2. pd.date_range(start='2018-05-01' ,periods = 100)# 产生100个Datetime
3. pd.date_range(start='2018-05-01' ,periods = 100,freq = 'W')#每周一间隔
freq =‘H’ 每小时为间隔
freq = ‘5H’ 每5小时为间隔
freq = ‘D’ 每天为间隔
freq = ‘W’ 每周为分隔
freq =‘W-MON’ 每周为分隔,周一为间隔的起点

数据类型转换为时间序列类型

  1. 设置列为DataFrame类型
* df['col1'] = pd.to_datetime(df['col1'],format = '%Y-%m-%d')
* #format 设置显示日期精度、格式
  1. 设置索引为DatetimeIndex类型
# 读取文件时,将date列读取为index,此时索引类型为obj
df = pd.read_csv('1.csv',index_col= 'date')

# 将索引类型更改为DatetimeIndex
df.index = pd.DatetimeIndex(df.index)# 可直接多索引进行操作

注意index的值为日期,所以才能转换为Datetime

  1. 对时间序列的切片
df = pd.DataFrame(np.random.randn(100,4),index  = pd.date_range('20181031',periods=100,freq='W'))
df.loc['2018']
df.loc['2018-11']

0 1 2 3
2018-11-04 1.512598 0.049858 -0.958455 0.714407
2018-11-11 -0.906760 1.118072 -0.705264 0.323554
2018-11-18 0.789005 -1.583082 0.463199 -1.340168
2018-11-25 0.532485 -1.433163 0.521303 1.221758

Ser = pd.Series(np.random.randn(1000),pd.date_range('20181031',periods=1000))
Ser['2018']
Ser['20181111':'20181116']

2018-11-11 0.360134
2018-11-12 1.886571
2018-11-13 -0.609659
2018-11-14 0.703976
2018-11-15 -1.182582
2018-11-16 -0.080813
Freq: D, dtype: float64

  1. 换算精确到年、月、日——单位换算
df.col_1.values.astype('datetime64[M]')
#假设换算前列单位为ns,现在则为month

|datetime64[Y]|年份|
|datetime64[M]|月份|
|datetime64[D]|天|
为精确到年月日格式

5. 其他
```python
np.datetime64('today') #今天,单位天

* /np.timedelta64[1,'D']
	1. 消除单位'days'
	2. datetime列除以
	3. eg,假设df.col_1为时间序列,精确度为day:
df.col_1_new = df.col_1/np.timedelta64[1,'D']
df.col_1_new的单位day就消除了,可以看作只是一列数字了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章