Titanic Data Analysis

By K.Nikhil

The titanic dataset investigation is to determine what factors made it more likely that a person survived on the Titanic. class, sex, and age. The invistigation says higher class ,females-passengers had greatest possibility of surviving

Data Types adjustments

In [17]:
import pandas as pd
from __future__ import division
import numpy as np
import matplotlib as mt
sinkingship=pd.read_csv("titanic-data.csv")
#CSV is in correct format so not changing any datatypes
#Croping the name to make dataframe to visualize easily
def cropname(name):
    spliter = name.split(",")
    return spliter[1]
sinkingship['Name'].apply(cropname)
#removing NAN age rows
cleanage = sinkingship[sinkingship['Age'].notnull()]
Twentyf= cleanage['Age'].quantile(q=0.25)
Seventyf= cleanage['Age'].quantile(q=0.75)
max = (Seventyf - Twentyf) * 1.5 + Seventyf
min = Twentyf - (Seventyf-Twentyf) * 1.5
clean_age = cleanage[(cleanage['Age'] > min) & (cleanage['Age'] < max)]

Raw data with cropped name

In [18]:
sinkingship.describe()
Out[18]:
PassengerId Survived Pclass Age SibSp Parch Fare
count 891.000000 891.000000 891.000000 714.000000 891.000000 891.000000 891.000000
mean 446.000000 0.383838 2.308642 29.699118 0.523008 0.381594 32.204208
std 257.353842 0.486592 0.836071 14.526497 1.102743 0.806057 49.693429
min 1.000000 0.000000 1.000000 0.420000 0.000000 0.000000 0.000000
25% 223.500000 0.000000 2.000000 20.125000 0.000000 0.000000 7.910400
50% 446.000000 0.000000 3.000000 28.000000 0.000000 0.000000 14.454200
75% 668.500000 1.000000 3.000000 38.000000 1.000000 0.000000 31.000000
max 891.000000 1.000000 3.000000 80.000000 8.000000 6.000000 512.329200

Clean age factor

In [19]:
clean_age.describe()
Out[19]:
PassengerId Survived Pclass Age SibSp Parch Fare
count 703.000000 703.000000 703.000000 703.000000 703.000000 703.000000 703.000000
mean 449.290185 0.411095 2.244666 29.072077 0.519203 0.435277 34.785093
std 258.604497 0.492383 0.835397 13.728478 0.934836 0.858015 53.255433
min 1.000000 0.000000 1.000000 0.420000 0.000000 0.000000 0.000000
25% 224.000000 0.000000 1.000000 20.000000 0.000000 0.000000 8.050000
50% 444.000000 0.000000 3.000000 28.000000 0.000000 0.000000 15.741700
75% 678.500000 1.000000 3.000000 38.000000 1.000000 1.000000 33.000000
max 891.000000 1.000000 3.000000 64.000000 5.000000 6.000000 512.329200

Investigating Factors

In [20]:
totalpassengers = len(sinkingship)
statuscount=sinkingship.groupby('Survived')['PassengerId'].count()
survived = sinkingship[sinkingship["Survived"]==1]
notsurvived = sinkingship[sinkingship["Survived"]==0]
Totalsurvivedpassengers = statuscount[1]
Totalnonsurvivedpassengers = statuscount[0]
surviveperc = (Totalsurvivedpassengers*100)/totalpassengers
deathperc = (Totalnonsurvivedpassengers*100)/totalpassengers
#Class wise passengers

classcount = sinkingship.groupby('Pclass')['PassengerId'].count()
class_1_passengers = classcount[1]
class_2_passengers = classcount[2]
class_3_passengers = classcount[3]
#The Panda dataframe of classes counts of SUrvived /death passengers
theclassesdetial=pd.crosstab(sinkingship['Pclass'],sinkingship['Survived'])
type(theclassesdetial)
Out[20]:
pandas.core.frame.DataFrame
In [21]:
class_1_passengers_survived=theclassesdetial[0][1]
class_1_passengers_death=theclassesdetial[1][1]
class1_survived_percentage=(class_1_passengers_survived*100)/class_1_passengers
class1_death_percentage=(class_1_passengers_death*100)/class_1_passengers
total_class1_survived_percentage=(class_1_passengers_survived*100)/totalpassengers
total_class1_death_percentage=(class_1_passengers_death*100)/totalpassengers

class_2_passengers_survived=theclassesdetial[0][2]
class_2_passengers_death=theclassesdetial[1][2]
class2_survived_percentage=(class_2_passengers_survived*100)/class_2_passengers
class2_death_percentage= (class_2_passengers_death*100)/class_2_passengers
total_class2_survived_percentage=(class_2_passengers_survived*100)/totalpassengers
total_class2_death_percentage=(class_2_passengers_death*100)/totalpassengers

class_3_passengers_survived=theclassesdetial[0][3]
class_3_passengers_death=theclassesdetial[1][3]
class3_survived_percentage=(class_3_passengers_survived*100)/class_3_passengers
class3_death_percentage= (class_3_passengers_death*100)/class_3_passengers
total_class3_survived_percentage=(class_3_passengers_survived*100)/totalpassengers
total_class3_death_percentage=(class_3_passengers_death*100)/totalpassengers

nmales_survived=len(survived[survived['Sex'] == 'male'])
nmales_died=len(notsurvived[notsurvived['Sex'] == 'male'])
nfemales_survived=len(survived[survived['Sex'] == 'female'])
nfemales_died=len(notsurvived[notsurvived['Sex'] == 'female'])

survivorages = clean_age[clean_age['Survived'] == 1]
nonsurvivorages = clean_age[clean_age['Survived'] == 0]
def printthesinkingstat():
    print "Totalpassengers traveling :"+str(totalpassengers)
    print "Total Survivers :"+str(Totalsurvivedpassengers)
    print "Total Deaths :"+str(Totalnonsurvivedpassengers)
    print "survivers percentage :"+str(surviveperc)
    print "deaths percentage :"+str(deathperc)
    print "class_1_passengers :"+str(class_1_passengers)
    print "class_1_passengers_survived :"+str(class_1_passengers_survived)
    print "class_1_passengers_death :" +str(class_1_passengers_death)
    print "class_1_passengers percentage:"+str((class_1_passengers*100)/totalpassengers)
    print "class_1_survived_percentage :"+str(class1_survived_percentage)
    print "class_1_death_percentage :"+str(class1_death_percentage)
    print "Total_class_1_survived_percentage :"+str(total_class1_survived_percentage)
    print "total_class_1_death_percentage :"+str(total_class1_death_percentage)
    print "class_2_passengers :"+str(class_2_passengers)
    print "class_2_passengers_survived :"+str(class_2_passengers_survived)
    print "class_2_passengers_death :"+str(class_2_passengers_death)
    print "class_2_passengers percentage:"+str((class_2_passengers*100)/totalpassengers)
    print "class_2_survived_percentage :"+str(class2_survived_percentage)
    print "class_2_death_percentage :"+str(class2_death_percentage)
    print "Total_class_2_survived_percentage :"+str(total_class2_survived_percentage)
    print "total_class_2_death_percentage :"+str(total_class2_death_percentage)
    print "class_3_passengers :"+str(class_3_passengers)
    print "class_3_passengers_survived :"+str(class_3_passengers_survived)
    print "class_3_passengers_death :"+str(class_3_passengers_death)
    print "class_3_passengers percentage:"+str((class_3_passengers*100)/totalpassengers)
    print "class_3_survived_percentage :"+str(class3_survived_percentage)
    print "class_3_death_percentage :"+str(class3_death_percentage)
    print "Total_class_3_survived_percentage :"+str(total_class3_survived_percentage)
    print "total_class_3_death_percentage :"+str(total_class3_death_percentage)
    print "Number of males survived :"+str(nmales_survived)
    print "No of males died :"+str(nmales_died)
    print "Number of females survived :" + str(nfemales_survived)
    print "No of females died :" + str(nfemales_died)

printthesinkingstat()
Totalpassengers traveling :891
Total Survivers :342
Total Deaths :549
survivers percentage :38.3838383838
deaths percentage :61.6161616162
class_1_passengers :216
class_1_passengers_survived :80
class_1_passengers_death :136
class_1_passengers percentage:24.2424242424
class_1_survived_percentage :37.037037037
class_1_death_percentage :62.962962963
Total_class_1_survived_percentage :8.97867564534
total_class_1_death_percentage :15.2637485971
class_2_passengers :184
class_2_passengers_survived :97
class_2_passengers_death :87
class_2_passengers percentage:20.6509539843
class_2_survived_percentage :52.7173913043
class_2_death_percentage :47.2826086957
Total_class_2_survived_percentage :10.88664422
total_class_2_death_percentage :9.76430976431
class_3_passengers :491
class_3_passengers_survived :372
class_3_passengers_death :119
class_3_passengers percentage:55.1066217733
class_3_survived_percentage :75.7637474542
class_3_death_percentage :24.2362525458
Total_class_3_survived_percentage :41.7508417508
total_class_3_death_percentage :13.3557800224
Number of males survived :109
No of males died :468
Number of females survived :233
No of females died :81

Survivors/Deaths plotting based on different Classes

In [22]:
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
trace1 = go.Bar(
    x=['CLASS1', 'CLASS2', 'CLASS3'],
    y=[class_1_passengers_survived,class_2_passengers_survived, class_3_passengers_survived],
    name='Survived'
)
trace2 = go.Bar(
    x=['CLASS1', 'CLASS2', 'CLASS3'],
    y=[class_1_passengers_death,class_2_passengers_death,class_3_passengers_death],
    name='Death'
)

data = [trace1, trace2]
layout = go.Layout(
    barmode='group',
    title='Survivors/Deaths plotting based on different Classes of passengers',
    xaxis=dict(
        title='Different classes of Passengers',
        titlefont=dict(
            family='Courier New, monospace',
            size=18,
            color='#7f7f7f'
        )
    ),
    yaxis=dict(
        title='Frequency-count',
        titlefont=dict(
            family='Courier New, monospace',
            size=18,
            color='#7f7f7f'
        )
    )

)

fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='grouped-bar')

Discussion

From the above stats we can say that class1 is 24% of total passengers strength where 62.9% of 24% total passengers are asurvived class2 is 20.6% of total passenngers strength where 47.2% of 20.6% total passengers are survived class3 is 55.10% of total passengers strength where 24% of 55.10% are survived the above data shows that the higher the class the better the survival chance From below chisquare and pvalue we can say that class plays a crucial role in surviving factor

In [23]:
import scipy.stats 
class_1_passengers_survived = 80
class_2_passengers_survived  = 97
class_3_passengers_survived = 372
class_1_passengers_died= 136
class_2_passengers_died= 87
class_3_passengers_died=119
obs = np.array([[class_1_passengers_survived,class_2_passengers_survived,class_3_passengers_survived], [class_1_passengers_died, class_2_passengers_died, class_3_passengers_died]])
chisquare, p, dof, ex = scipy.stats.chi2_contingency(obs, correction=False)
print "pvalue: ", p
print "Chisquaredscore: ", chisquare
pvalue:  4.5492517113e-23
Chisquaredscore:  102.888988757

Plotting Survivors/Deaths for males and females

In [24]:
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
fig = {
  "data": [
    {
      "values": [nmales_survived,nmales_died],
      "labels": [
        "Male-Survived",
        "Males-died"
      ],
      "domain": {"x": [0, .48]},
      "name": "GHG Emissions",
      "hoverinfo":"label+percent+name",
      "hole": .4,
      "type": "pie"
    },     
    {
      "values": [nfemales_survived,nfemales_died],
      "labels": [
       "Females-Survived",
       "Females-died"
      ],
      "textposition":"inside",
      "domain": {"x": [.52, 1]},
      "hoverinfo":"label+percent+name",
      "hole": .4,
      "type": "pie"
    }],
  "layout": {
        "title":"Survivors/Deaths for males and females",
        "annotations": [
            {
                "font": {
                    "size": 20
                },
                "showarrow": False,
                "text": "Males",
                "x": 0.20,
                "y": 0.5
            },
            {
                "font": {
                    "size": 20
                },
                "showarrow": False,
                "text": "Females",
                "x": 0.8,
                "y": 0.5
            }
        ]
    }
}
iplot(fig)

Discussion

To test the statistical difference between the genders, we conduct a difference in proportions test using a

I am following two titled test by spliiting the alpha level AlphaLevel-Value: 0.05(5%)

We Will use two-titled to test the likelyhood weather it is likely or unlikely

Z-critical value of AlphaLevel of 2.5% on negative side is -1.96(According to table) Z-critical value of AlphaLevel of 2.5% on Positive side is 1.96(According to table)

H0:Null hypothesis HA:ALternative hypothesis

H0: male_survivals= female_survivals HA: male_survivals != female_survivals

p = ( male_survivals x total_males + female_survivals x total_females) / (total_males + total_females) p = (0.188908145581 577 + 0.742038216561 314) / (314 + 577) p = 0.384

s = sqrt( p (1-p) [(1/total_males) + (1/total_females)] ) s= sqrt( 0.384 (1-0.384) [(1/577) + (1/314)] ) s= 0.0341

z = ( male_survivals - female_survivals) / s z = (0.188908145581 - 0.742038216561) / 0.0341 z = -16.2

Since:-16.2 < -1.96, we are rejecting the null hypothesis. Indeed, statistical evidence shows that if you were a female you had a higher chance of surviving.

Plotting Survivors and deaths by Age

In [25]:
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
x0 = survivorages['Age']
x1 = nonsurvivorages['Age']

Survivers = go.Histogram(
    x=x0,
    name='Survivers',
    opacity=0.50,
    
)
Died_passengers = go.Histogram(
    x=x1,
    name='Died_passengers',
    opacity=0.25
)
data = [Survivers,Died_passengers]
layout = go.Layout(
    barmode='overlay',
    title='Plot based on Survivors and deaths by age factor',
    xaxis=dict(
        title='Passenger Age',
        titlefont=dict(
            family='Courier New, monospace',
            size=18,
            color='#7f7f7f'
        )
    ),
    yaxis=dict(
        title='Frequency-count',
        titlefont=dict(
            family='Courier New, monospace',
            size=18,
            color='#7f7f7f'
        )
    )
)
fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='grouped-bar')

Conclusion

Limitations before proceeding In 891 rows of data, 179 were missing important fields such as age. Cabin location is useless unless there is some another column which represents cabin column Factors for Survival Recall that the initial question was that upper class passengers, females, and young people had a larger chance of surviving. Class From the above stats we can say that class1 is 24% of total passengers strength where 62.9% of 24% total passengers are asurvived class2 is 20.6% of total passenngers strength where 47.2% of 20.6% total passengers are survived class3 is 55.10% of total passengers strength where 24% of 55.10% are survived the above data shows that the higher the class the better the survival chance Gender The statistical evidence shows that male is having smaller chance of surviving on the Titanic than a female. 18.9% of the males survived and 74.2% of the females survived. Age A histogram plot is created on age and survivability. There was no statistical evidence pointing to the fact that age played a role in survivability. Final Words The best chance for survival is passenger's class.Since first-class passengers received a "first-class ticket" to safety,first class passengers had been given higher prioirity to travel with life saving boats, third class passengers are the once who died the most. It is the disadvantage for class-3 passengers to be at lower decks. Gender also played a close role "Women and children" was certainly a phrase that nicely sums up this gender discrepancy (not the children part though). Age didnt impact the passenger's survival.