文章目录
Study:day9-Numpy科学计算与Pandas数据分析
1.1 时序数据
- 时序数据的基本对象
- 时间戳date times概念(使用频率最高)
- 时间差:times deltas 概念
- 时间段:times spans 概念
1.1.1 基本时间生成
date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize: ‘bool’ = False, name: ‘Hashable | None’ = None, inclusive: ‘IntervalClosedType’ = ‘both’, *, unit: ‘str | None’ = None, **kwargs) -> ‘DatetimeIndex’
- start:日期开始的时间
- end:日期结束的时间
- freq:时间间隔,默认为’D’,表示一天
- s :秒
- D:一天
- h:一小时
- ME:月
- YE:年
- periods:生成时间序列的个数
import pandas as pd
# 生成22年1月到24年9月所有月份的数据
date = pd.date_range('2022-01-01','2024-09-30',freq='ME')
1.1.2 时间的转换 【重点】
table = pd.DataFrame(date,columns=['date'])
table.dtypes
date datetime64[ns]
dtype: object
# 将datetime64ns格式转为普通的字符串时间 【重点】
table['str_date'] = table['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
# 将字符串时间转为datetime64ns格式 【重点】
table['datetime64ns_date'] = pd.to_datetime(table['str_date'])
table.info() # 查看数据集的基本信息,一般用于查看变量类型,是否有缺失值
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 33 entries, 0 to 32
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 date 33 non-null datetime64[ns]
1 str_date 33 non-null object
2 datetime64ns_date 33 non-null datetime64[ns]
dtypes: datetime64[ns](2), object(1)
memory usage: 924.0+ bytes
table[‘str_date’] = table[‘date’].apply(lambda x:x.strftime(‘%Y-%m-%d %H:%M:%S’))
- %Y:年份
- %m:月份
- %d:日
- %H:小时
- %M:分钟
- %S:秒
1.1.3 时序数据的应用【重点】
table['year'] = table['date'].dt.year # 提取出时序数据中的年份
table['month'] = table['date'].dt.month # 提取出时序数据中的月份
table['day'] = table['date'].dt.day # 提取出时序数据中的日
table['hour'] = table['date'].dt.hour # 提取出时序数据中的小时
table['minute'] = table['date'].dt.minute # 提取出时序数据中的分钟
table['second'] = table['date'].dt.second # 提取出时序数据中的秒
table['week_num'] = table['date'].dt.dayofweek # 提取出时序数据中的星期,其中0是周一,1是周二
table['en_week_name'] = table['date'].dt.day_name() # 提取出时序数据中的星期,返回英文星期名称
table['en_month_name'] = table['date'].dt.month_name() # 提取出时序数据中的月份,返回英文月份名称
table['day_num_inyear'] = table['date'].dt.dayofyear # 提取出时序数据中的天,一年中的第几天
table['week_num_inyear'] = table['date'].dt.isocalendar()['week'] # 提取出时序数据中的星期,一年中的第几个星期
table['quarter'] = table['date'].dt.quarter # 提取出时序数据中的季度
table['day_of_month'] = table['date'].dt.daysinmonth # 提取出时序数据中的日,一个月中的第几天
table['year_start'] = table['date'].dt.is_year_start # 判断是否是一年的开始
table['year_end'] = table['date'].dt.is_year_end # 判断是否是一年的结束
table['month_start'] = table['date'].dt.is_month_start # 判断是否是一个月的开始
table['month_end'] = table['date'].dt.is_month_end # 判断是否是一个月的结束
table['quarter_start'] = table['date'].dt.is_quarter_start # 判断是否是一个季度的开始
table['quarter_end'] = table['date'].dt.is_quarter_end # 判断是否是一个季度的结束
table['date'].dt.isocalendar()['day'].unique() # 返回星期数,1-7,
table['date'].dt.dayofweek.unique() # 返回星期数0-6
array([0, 3, 5, 1, 6, 2, 4])
- 将table中的月份名称,星期名称,映射为中文名称,然后将年月季度开始的值,True映射是,False映射为否
weekdays_dict = {
'Saturday': '星期六',
'Sunday': '星期日',
'Monday': '星期一',
'Tuesday': '星期二',
'Wednesday': '星期三',
'Thursday': '星期四',
'Friday': '星期五'
}
months_dict = {
'January': '一月',
'February': '二月',
'March': '三月',
'April': '四月',
'May': '五月',
'June': '六月',
'July': '七月',
'August': '八月',
'September': '九月',
'October': '十月',
'November': '十一月',
'December': '十二月'
}
table['cn_week_name'] = table['en_week_name'].map(weekdays_dict)
table['cn_month_name'] = table['en_month_name'].map(months_dict)
# table.loc[:,'year_start':'quarter_end'] = table.loc[:,'year_start':'quarter_end'].map(lambda x:'是'if x==True else '否')
1.1.4 时序索引设置
table.set_index('date',inplace=True) # 将日期设置为索引
table.loc['2022-08'] # 可以很轻松提取指定数据
table.loc['2022-08-15':'2022-09'] # 提取22年8月15日到9月的所有数据
table[table.index.is_month_start] # 提取每个月第一天数据
table[table.index.day_of_week >= 5] # 提取所有星期六和星期日数据
table.head(2)
str_date | datetime64ns_date | year | month | day | hour | minute | second | week_num | en_week_name | ... | quarter | day_of_month | year_start | year_end | month_start | month_end | quarter_start | quarter_end | cn_week_name | cn_month_name | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
date | |||||||||||||||||||||
2022-01-31 | 2022-01-31 | 2022-01-31 | 2022 | 1 | 31 | 0 | 0 | 0 | 0 | Monday | ... | 1 | 31 | False | False | False | True | False | False | 星期一 | 一月 |
2022-02-28 | 2022-02-28 | 2022-02-28 | 2022 | 2 | 28 | 0 | 0 | 0 | 0 | Monday | ... | 1 | 28 | False | False | False | True | False | False | 星期一 | 二月 |
2 rows × 23 columns
1.1.5 取整操作
s = pd.Series(pd.date_range('2024-09-19','2024-09-20',freq='45min'))
s.dt.round('h') # 四舍五入取整,超过30向上取,小于等于30向下取
s.dt.floor('h') # 向下取整
s.dt.ceil('h') # 向上取整
0 2024-09-19 00:00:00
1 2024-09-19 01:00:00
2 2024-09-19 02:00:00
3 2024-09-19 03:00:00
4 2024-09-19 03:00:00
5 2024-09-19 04:00:00
6 2024-09-19 05:00:00
7 2024-09-19 06:00:00
8 2024-09-19 06:00:00
9 2024-09-19 07:00:00
10 2024-09-19 08:00:00
11 2024-09-19 09:00:00
12 2024-09-19 09:00:00
13 2024-09-19 10:00:00
14 2024-09-19 11:00:00
15 2024-09-19 12:00:00
16 2024-09-19 12:00:00
17 2024-09-19 13:00:00
18 2024-09-19 14:00:00
19 2024-09-19 15:00:00
20 2024-09-19 15:00:00
21 2024-09-19 16:00:00
22 2024-09-19 17:00:00
23 2024-09-19 18:00:00
24 2024-09-19 18:00:00
25 2024-09-19 19:00:00
26 2024-09-19 20:00:00
27 2024-09-19 21:00:00
28 2024-09-19 21:00:00
29 2024-09-19 22:00:00
30 2024-09-19 23:00:00
31 2024-09-20 00:00:00
32 2024-09-20 00:00:00
dtype: datetime64[ns]
s = pd.Series(pd.date_range('2024-09-19','2024-09-20',freq='45min'))
s.dt.round('2h') # 四舍五入取整,超过30向上取,小于等于30向下取
s.dt.floor('2h') # 向下取整
s.dt.ceil('2h') # 向上取整
0 2024-09-19 00:00:00
1 2024-09-19 02:00:00
2 2024-09-19 02:00:00
3 2024-09-19 04:00:00
4 2024-09-19 04:00:00
5 2024-09-19 04:00:00
6 2024-09-19 06:00:00
7 2024-09-19 06:00:00
8 2024-09-19 06:00:00
9 2024-09-19 08:00:00
10 2024-09-19 08:00:00
11 2024-09-19 10:00:00
12 2024-09-19 10:00:00
13 2024-09-19 10:00:00
14 2024-09-19 12:00:00
15 2024-09-19 12:00:00
16 2024-09-19 12:00:00
17 2024-09-19 14:00:00
18 2024-09-19 14:00:00
19 2024-09-19 16:00:00
20 2024-09-19 16:00:00
21 2024-09-19 16:00:00
22 2024-09-19 18:00:00
23 2024-09-19 18:00:00
24 2024-09-19 18:00:00
25 2024-09-19 20:00:00
26 2024-09-19 20:00:00
27 2024-09-19 22:00:00
28 2024-09-19 22:00:00
29 2024-09-19 22:00:00
30 2024-09-20 00:00:00
31 2024-09-20 00:00:00
32 2024-09-20 00:00:00
dtype: datetime64[ns]
1.1.6 时序数据综合练习
data = pd.read_csv('./data/all_contry_histoary_data.csv',low_memory=False)
任务1: 可以先将日期转换为datetime64ns这种时间格式,将日期设置为索引,然后提取2021年的数据,将该数据赋值给新的变量data2022
任务2: 在data2022中,提取年月日,星期名称,月份的名称,季度
任务3: 在data2022中,共有200多个国家,我们想知道在这一年中,哪些国家哪些日期没有更新数据
data['date'] = pd.to_datetime(data['date'])
data.set_index('date',inplace=True)
data2022 = data.loc['2021'].copy()
data2022.reset_index(inplace=True)
data2022['year'] = data2022['date'].dt.year
data2022['month'] = data2022['date'].dt.month
data2022['day'] = data2022['date'].dt.day
data2022['day_name'] = data2022['date'].dt.day_name() # 提取出时序数据中的星期,返回英文星期名称
data2022['month_name'] = data2022['date'].dt.month_name() # 提取出时序数据中的月份,返回英文月份名称
data2022['quarter'] = data2022['date'].dt.quarter # 提取出时序数据中的季度
date = pd.DataFrame(pd.date_range('2021-01-01','2021-12-31',freq='D'))[0].apply(lambda x:x.strftime('%Y-%m-%d')).tolist()
data2022['date'] = data2022['date'].apply(lambda x:x.strftime('%Y-%m-%d')).tolist()
dp = data2022.groupby('name')['date'].apply(lambda x:list((set(date) - set(x)))).reset_index()