Python pandas,时间序列,生成时间序列 date_range(),时间序列索引,字符串转换成时间序列类型 to_datetime() - Go语言中文社区

Python pandas,时间序列,生成时间序列 date_range(),时间序列索引,字符串转换成时间序列类型 to_datetime()


pandas生成时间序列:

pd.date_range(start=None, end=None, periods=None, freq='D')

start表示开始时间,end表示结束时间,periods表示生成时间序列的个数,freq表示频率。

一般是start、end和freq配合使用,或者start、periods和freq配合使用。 (end和periods不会同时使用)

 

demo.py(生成时间序列,date_range(),时间序列索引):

# coding=utf-8
import numpy as np
import pandas as pd


# date_range()生成时间序列
dt1 = pd.date_range(start="20190101", end="20190831", freq="D")  # freq="D"表示频率为每一天
print(dt1)  # <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
'''
DatetimeIndex(['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04',
               '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08',
               '2019-01-09', '2019-01-10',
               ...
               '2019-08-22', '2019-08-23', '2019-08-24', '2019-08-25',
               '2019-08-26', '2019-08-27', '2019-08-28', '2019-08-29',
               '2019-08-30', '2019-08-31'],
              dtype='datetime64[ns]', length=243, freq='D')
'''

# 生成时间序列  periods=10表示生成10个时间序列  freq="10D"表示频率为10天
dt2 = pd.date_range(start="20190101", periods=10, freq="10D")
print(dt2)
'''
DatetimeIndex(['2019-01-01', '2019-01-11', '2019-01-21', '2019-01-31',
               '2019-02-10', '2019-02-20', '2019-03-02', '2019-03-12',
               '2019-03-22', '2019-04-01'],
              dtype='datetime64[ns]', freq='10D')
'''


# DatetimeIndex时间序列可以直接赋值给索引
df = pd.DataFrame(np.arange(20).reshape((10, 2)), index=dt2)
print(df)
'''
             0   1
2019-01-01   0   1
2019-01-11   2   3
2019-01-21   4   5
2019-01-31   6   7
2019-02-10   8   9
2019-02-20  10  11
2019-03-02  12  13
2019-03-12  14  15
2019-03-22  16  17
2019-04-01  18  19
'''

 

demo.py(字符串转换成时间序列类型,to_datetime()):

# coding=utf-8
import pandas as pd


# 带有时间列的DataFrame
df = pd.DataFrame([{"name":"张三","birthday":"2018年1月1日"},{"name":"李四","birthday":"2018年8月8日"}])
print(df)
'''
    birthday    name
0  2018年1月1日  张三
1  2018年8月8日  李四
'''


# to_datetime() 将字符串类型转换成时间序列类型  (format参考python的日期格式)
dt_index = pd.to_datetime(df["birthday"], format="%Y年%m月%d日")  # format参数可以省略。 如果时间字符串中有中文,需要format指定格式。
print(dt_index)  # dtype是时间序列类型。 (可以把时间序列当成索引)
'''
0   2018-01-01
1   2018-08-08
Name: birthday, dtype: datetime64[ns]
'''

# 可以把时间序列当成索引
df.index = dt_index
print(df)
'''
             birthday name
birthday                  
2018-01-01  2018年1月1日   张三
2018-08-08  2018年8月8日   李四
'''

 

频率freq参数参考:

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/houyanhua1/article/details/87881424
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 18:41:52
  • 阅读 ( 1225 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢