当前位置: 首页 > news >正文

Python分析假期对美国出生率的影响

背景

1、数据集下载

birthsHistorical US birth data culled from the CDC website - jakevdp/data-CDCbirthsicon-default.png?t=O83Ahttps://github.com/jakevdp/data-CDCbirths

2、数据集介绍

此数据来自美国疾病控制和预防中心,并通过 Google 的 BigQuery Web UI 使用以下查询进行编译:

SELECTyear, month, day,IF (is_male, 'M', 'F') AS gender,SUM(record_weight) as births
FROM[publicdata:samples.natality]
GROUP BYyear, month, day, gender
ORDER BYyear, month, day, gender

它被汇总以符合他们的使用条款。 数据于 2015 年 6 月 9 日访问。

请注意,Andrew Gelman 和他的小组已经对这些数据进行了相当广泛的分析;参见 this post (英文)。

一、读取数据

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
from datetime import datetime
%matplotlib inline

二、数据分析预处理

#假期对美国出生率的影响
births=pd.read_csv('./births.csv')
quartiles = np.percentile(births['births'], [25, 50, 75])
mu, sig = quartiles[1], 0.74 * (quartiles[2] - quartiles[0])
births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)')
births['day'] = births['day'].astype(int)
births.index = pd.to_datetime(10000 * births.year +100 * births.month +births.day, format='%Y%m%d')
births_by_date = births.pivot_table('births',[births.index.month, births.index.day])
births_by_date.index = [datetime(2012, month, day)for (month, day) in births_by_date.index]#导入datetime模块
births_by_date.index

DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',
               '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',
               '2012-01-09', '2012-01-10',
               ...
               '2012-12-22', '2012-12-23', '2012-12-24', '2012-12-25',
               '2012-12-26', '2012-12-27', '2012-12-28', '2012-12-29',
               '2012-12-30', '2012-12-31'],
              dtype='datetime64[ns]', length=366, freq=None)

三、可视化

fig,ax=plt.subplots(figsize=(12,4)) 
births_by_date.plot(ax=ax)
ax.annotate("New Year's Day",xy=("2012-1-1",4100),xycoords='data',xytext=(50,-30),textcoords='offset points',         arrowprops=dict(arrowstyle='->',                 connectionstyle='arc3,rad=-0.2'))
ax.annotate("Independence Day",xy=('2012-7-4',4250),xycoords='data',          bbox=dict(boxstyle='round',fc='none',ec='gray'),         xytext=(10,-40),textcoords="offset points",ha='center',  arrowprops=dict(arrowstyle='->'))
ax.annotate("Labor Day",xy=('2012-9-4',4850),xycoords='data',ha='center',         xytext=(0,-20),textcoords='offset points')
ax.annotate('',xy=('2012-9-1',4850),xytext=('2012-9-7',4850),         xycoords='data',textcoords='data',   arrowprops={'arrowstyle':'|-|,widthA=0.2,widthB=0.2',})
ax.annotate('Halloween',xy=('2012-10-31',4600),xycoords='data',       xytext=(-80,-40),textcoords='offset points',        arrowprops=dict(arrowstyle='fancy',                     fc='0.6',ec='none',                       connectionstyle='angle3,angleA=0,angleB=-90'))
ax.annotate("Thanksgiving",xy=('2012-11-25',4500),xycoords='data',           xytext=(-120,-60),textcoords='offset points',           bbox=dict(boxstyle='round4,pad=.5',fc='0.9'),          arrowprops=dict(arrowstyle='->',                          connectionstyle='angle,angleA=0,angleB=80,rad=20'))
ax.annotate('Christmas',xy=('2012-12-25',3850),xycoords='data',           xytext=(-30,0),textcoords='offset points',           size=13,ha='right',va='center',           bbox=dict(boxstyle='round',alpha=0.1),         arrowprops=dict(arrowstyle='wedge,tail_width=0.5',alpha=0.1));
ax.set(title='USA births by day of year (1969-1988)',ylabel='average daily births')         
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%h'))
ax.set_ylim(3600,5400)
# ax.grid(True)
plt.show()

 

# Plot the results
fig, ax = plt.subplots(figsize=(8, 6))
births.groupby(dates)['births'].mean().plot(ax=ax)# Label the plot
ax.text('2012-1-1', 3950, "New Year's Day")
ax.text('2012-7-4', 4250, "Independence Day", ha='center')
ax.text('2012-9-4', 4850, "Labor Day", ha='center')
ax.text('2012-10-31', 4600, "Halloween", ha='right')
ax.text('2012-11-25', 4450, "Thanksgiving", ha='center')
ax.text('2012-12-25', 3800, "Christmas", ha='right')
ax.set(title='USA births by day of year (1969-1988)',ylabel='average daily births',xlim=('2011-12-20','2013-1-10'),ylim=(3700, 5400));# Format the x axis with centered month labels
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.NullFormatter())
ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%h'));
ax.set_ylim(3600, 5400)plt.show()

 

http://www.lryc.cn/news/471311.html

相关文章:

  • 机械臂笛卡尔空间轨迹规划
  • 红队工具---Behinder学习
  • k8s 1.28.2 集群部署 NFS server 和 NFS Subdir External Provisioner
  • 前端零基础入门到上班:【Day1】什么是前端?
  • 搜索二叉树 Binary Search Tree(BST)
  • 数据库表字段插入bug
  • 信创环境模拟:X86架构下部署搭建aarch64的ARM虚拟机
  • TSO的资料
  • OpenCV视觉分析之目标跟踪(3)实现基于金字塔的 Lucas-Kanade 算法来进行稀疏光流计算的类SparsePyrLKOpticalFlow的使用
  • 乐维网管平台(一):如何精准掌控 IP 管理
  • React-Route新版本(v6或以上)用法示例
  • 卡方检验方法概述与类型——四格表和R*C表卡方检验案例
  • 在浏览器和Node.js环境中使用Puppeteer的Rollup与Webpack打包指南
  • GPT论文整理提示词
  • 在培训班学网络安全有用吗
  • Flink CDC系列之:理解学习YARN模式
  • langgraph入门
  • 【Python】爬虫程序打包成exe
  • 【力扣专题栏】两两交换链表中的节点,如何实现链表中两两相邻节点的交换?
  • 埋点采集的日志数据常见的格式简介
  • 基于SSM高考志愿辅助填报系统设计与实现
  • elasticsearch 8.x 插件安装(六)之Hanlp插件
  • 排序算法简记
  • Stable diffusion inference 多卡并行
  • Docker:namespace环境隔离 CGroup资源控制
  • 鼠标增强工具 MousePlus v5.3.9.0 中文绿色版
  • Android 圆形进度条CircleProgressView 基础版
  • 理解磁盘结构---CHS---LAB---文件系统
  • 我在1024谈华为
  • NVR小程序接入平台/设备EasyNVR多品牌NVR管理工具/设备视频监控解决方案