# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
df=pd.read_csv('../input/cdc-ussss-births-data-1969200/cdc_births_data.csv')
df
df['year'].unique()
df.describe()
df.info()
df.isna().sum()
"""
### Filling null values
"""
df.isna().sum()
df.fillna(0,inplace=True)
"""
removing day values greater than 99

"""
births=df[df['day']!=99].copy()

births['births'].describe()
"""
### Births q1=25% =4388, q3=50% =5300

"""
q1=4388
q3=5300
iqr=q3-q1
lower=q1 - 1.5*iqr
upper=q3+1.5*iqr
births.info()
final=births[births['births'].between(lower,upper)].copy()
final['year'].unique()
"""
### Creating Decade column
"""
final['decade']=(final['year']//10)*10
final
"""
### Nummber of births in each decade
"""
decade1=final.pivot_table(index='decade',values='births',aggfunc=sum)
decade1
"""
### pivote table to show number of males and females birth in each decade
"""
decades=final.pivot_table(index='decade',values='births',aggfunc=sum,columns='gender')
decades
data = [go.Bar(
    x=decades.index,
    y=decades.values.flatten(),
)]

layout = go.Layout(title='Number of births in decades',plot_bgcolor='#fafafa',paper_bgcolor='#fafafa')
fig = go.Figure(data=data, layout=layout )
fig.update_xaxes(showgrid=False, zeroline=False)
fig.update_traces(marker_color='#10a2e0', marker_line_color='red',
                  marker_line_width=1.5, opacity=0.6)
fig.update_yaxes(showgrid=False, zeroline=False)
fig.show()
decades2=final.pivot_table(index='decade',values='births',aggfunc=[sum,min,max,'mean'],columns='gender')
decades2
"""
### Line chart to show births trends in years
"""
line_chrt=final.groupby(['year','decade'])['births'].sum().reset_index()
fig = px.line(line_chrt, x='year',y='births', title='Line chart to show birth in each Year',color_discrete_sequence=px.colors.sequential.Plasma)
fig.update_xaxes(showgrid=False, zeroline=False)
fig.update_traces(marker_color='#5961d4', marker_line_color='#ac11ba',
                  marker_line_width=3)
fig.update_layout(paper_bgcolor='#d9d7ca',plot_bgcolor='#d9d7ca')
fig.update_yaxes(showgrid=False, zeroline=False)
fig.update_xaxes(

    ticks="outside",
    tickson="boundaries",
    ticklen=40
)
fig.update_layout(
            xaxis=dict(
     
            )
        )
fig.show()
final['day']=final['day'].astype(int)
year=final['year']*10000
month=final['month']*100
day=final['day']
date=year+month+day
date=pd.to_datetime(date,format='%Y%m%d')
final.columns
final=final.set_index(date)
final['month_of_year']=final.index.strftime('%B')
final['dayofweek']=final.index.strftime('%A')
final
"""
### Number of births in each day
"""
final.groupby(['dayofweek'])['births'].sum().reset_index()
"""
### mean births in each day of every decade
"""

dfb=final.pivot_table(values='births',index='dayofweek',columns='decade',aggfunc='sum')
dfb.sort_index(ascending=True)
fig=px.bar(
    dfb.stack().reset_index().assign(decade=lambda d: d["decade"].astype(str)),
    color="decade",
    x="dayofweek",
    y=0,
    barmode="group",
)
fig.update_layout(title="No of birth in day in every decade", yaxis={"title":"Births"})
fig.show()
line_df=dfb.stack().reset_index().assign(decade=lambda d: d["decade"].astype(str))
line_df.head(3)
line_df1=line_df.groupby(['dayofweek'])[0].sum().reset_index()
px.line(line_df1,
       x='dayofweek',y=0
    )
"""
### table to show the mean births value in each day of every month



"""
c=final.pivot_table(index=[final.index.month,final.index.day],values='births')
c
el=[]
for month,day in c.index:
  d=pd.datetime(2020,month,day)
  el.append(d)
len(el)
# c.index=el
c['date']=el
c
fig=px.line(c,x='date',y='births' ,title=' weekly',hover_data=['births'],
            color_discrete_sequence=px.colors.sequential.Rainbow)

fig.update_xaxes(showgrid=False, zeroline=False)
fig.update_traces(marker_color='#5961d4', marker_line_color='#ac11ba',mode="lines",
                  marker_line_width=3)
fig.update_layout(paper_bgcolor='#d9d7ca',plot_bgcolor='#d9d7ca',hovermode='x')
fig.update_yaxes(showgrid=False, zeroline=False)
fig.update_xaxes(

    ticks="outside",
    tickson="boundaries",
    ticklen=40
)
fig.update_layout(
    
    hoverlabel=dict(
    
        bgcolor="white",
        font_size=16,
        font_family="Rockwell"
    )
)
fig.show()