Week-3 Assignment: Making Data Management Decisions:
I will continue this week with my selected variables and make a data management decision as follow:
For participants who answer no to the question Drank at least 1 alcoholic drink in the last 12 months? (variable S2AQ3), No need to answer the questions for variables S2AQ8A- How often drank any alcohol drink in last 12 months, And S2AQ8B- number of drinks last 12 months.
so, we need to recode this data as valid data rather to consider it as missing data, to implement this I used the following code:
alco_vars=['CONSUMER','S2AQ1','S2AQ2','S2AQ3','S2AQ8A','S2AQ8B']
data[var]=pd.to_numeric(data[var],errors='coerce')
#Recover valid data for the observations who answer no for the question Drank at least 12 alcoholic drink in last 12 months?
#set valid data for the variable S2AQ8A to dummy value 11
data.loc[(data[alco_vars[3]]!=9) &(data[alco_vars[4]].isnull()),alco_vars[4]]=11
#set valid data for the variable S2AQ8B to dummy value 100
data.loc[(data[alco_vars[3]]!=9) &(data[alco_vars[5]].isnull()),alco_vars[5]]=100
S2AQ8A-How often drank any alcohol in last 12 months
11.0 16116 37.4% ------- Recovered valid data (from S2AQ3)
NaN 31 0.07%-------Unknown from S2AQ3
S2AQ8B-number of drinks of any alcohol consumed on days when drank alcohol in last 12 months
100.0 16116 37.4%------- Recovered valid data (from S2AQ3)
NaN 31 0.07%-------- Unknown from S2AQ3
I used dummy code(11) for the valid data in S2AQ8A and 100 for valid data in S2AQ8B.
Set messing data (99) in S2AQ8A, S2AQ8B to nan:
##subset data to young adults age 18 to 25 who have drank at least 12 alcoholic drink in the last 12 months
sub1=data[(data['AGE']>=18) & (data['AGE']<=25) & (data['S2AQ2']==1)]
#make a copy of new subsetted data
alco_dep_a =sub1.copy()
# frequency distritions on new alco_dep_a data frame
print("Frequency and percentages for subset data( young adults age 18 to 25 who have drank at least 12 alcoholic drink in the last 12 months):")
alco_a_vars=['AGE','S2AQ2','S2AQ8A','S2AQ8B']
if var==alco_a_vars[0]:
print("adults age 18-25 by-{} tab".format(var))
elif var==alco_a_vars[1]:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{} adults who drank at least 12 alcoholic drink in the last 12 months".format(var))
elif var==alco_a_vars[2]:
#recode 99 values as missing for the variable S2AQ8A:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{}- How often drank any alcohol in last 12 months".format(var))
else:
#recode 99 values as missing for the variable S2AQ8B:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{}-Number of drinks of any alcohol consumed on days when drank alcohol in last 12 months".format(var))
c=alco_dep_a[var].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p=alco_dep_a[var].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=True).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c,' ':' ', 'Percent':p})
print(ferq_table)
Frequency and percentages for subset data( young adults age 18 to 25 who have drank at least 12 alcoholic drink in the last 12 months):
adults age 18-25 by-AGE tab
S2AQ2 adults who drank at least 12 alcoholic drink in the last 12 months
S2AQ8A- How often drank any alcohol in last 12 months
NaN 17 0.54% -------------missing data
S2AQ8B-Number of drinks of any alcohol consumed on days when drank alcohol in last 12 months
NaN 35 1.1%--------------missing data
3- Create secondary variables:
for variable S2AQ8A I will create a secondary NUMDRIMO_EST variable to compute number of drinks each participant consumes per month.
To achieve this, I will re-code this variable from 1-6 as below:
2- Nearly every day (5-6 times a week)
4- Once to 2 times a week
I think this coding is better and more accurate because a person cannot remember exactly what he consumed if the period become more than month.
- recoding values for S2AQ8A into a new variable, USFREQ the new code from 1-6:
#recording values for S2AQ8A and create new variables
#recoding values for S2AQ8A into a new variable, USFREQ the new code from 1-6
print('recoding values for S2AQ8A-How often drank alcohol in last 12 months?- in to a new variable,USFREQ ,the new code from 1-6')
recode1 = {1:1,2:2,3:3,4:4,5:4,6:5,7:6,8:6,9:6,10:6}
alco_dep_a['USFREQ']= alco_dep_a['S2AQ8A'].map(recode1)
c1=alco_dep_a['USFREQ'].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p1=alco_dep_a['USFREQ'].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c1,' ':' ', 'Percent':p1})
print(ferq_table)
recoding values for S2AQ8A-How often drank alcohol in last 12 months?- in to a new variable,USFREQ ,the new code from 1-6
- reverse the code values to indicate high frequency values take the high values and low frequency values take low values:
#reverse the code values to indicate high frequency values in the first and low frequency values in the last
print('reverse the code values to indicate high frequency take high values and low frequency take low values ')
#recoding values for S2AQ8A into a new variable, USFREQ1
recode2 = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
alco_dep_a['USFREQ1']= alco_dep_a['USFREQ'].map(recode2)
print(alco_dep_a['USFREQ1'].value_counts(sort=False,dropna=False).sort_index(ascending=True))
reverse the code values to indicate high frequency take high values and low frequency take low values
Name: USFREQ1, dtype: int64
It is reasonable to re-code the variable in order to capture more of its quantitative features. So, I choose values that reasonably
correspond to the number of times each individual drink in a usual Month. For example, if a person drinks every day this mean he drinks 30 days in usual month, if he drinks nearly every day (5-6 times a week) he drinks 22 days in a usual month and so on:
· Every day----------------------------------30 days a month
· Nearly every day (5-6 times a week) --------22 day a month
· 3 to 4 times a week------------------------14 days a month
· Once to 2 times a week----------------------5 days a month
· 2 to 3 times a month------------------------2.5 days a month
· Once or less a month------------------------1 day a month
The code that perform this task is below:
#recoding values for S2AQ8A into a new variable, USFREQMO
print('Create secondary variable USFREQMO to indicate how often you drank last 12 months as quantitative value per month')
recode3= {1: 30, 2: 22, 3: 14, 4: 5, 5: 2.5, 6: 1}
alco_dep_a['USFREQMO']= alco_dep_a['USFREQ'].map(recode3)
c1=alco_dep_a['USFREQMO'].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p1=alco_dep_a['USFREQMO'].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c1,' ':' ', 'Percent':p1})
print(ferq_table)
Create secondary variable USFREQMO to indicate how often you drank last 12 months as quantitative value per month
From this table we notice that most adults (31.61%) drink 5 day per month.
- Create the secondary variable: NUMDRIMO_EST and display the firs 25 rows:
#secondary variable multiplying the number of days drank/month and the approx number of drinks drank/day
alco_dep_a['NUMDRIMO_EST']=alco_dep_a['USFREQMO'] * alco_dep_a['S2AQ8A']
sub3=alco_dep_a[['IDNUM','S2AQ8A','USFREQMO','NUMDRIMO_EST']]
print(sub3.head(25))
#calculate the Frequency and precentages for the secondary variable NUMDRIMO_EST
c1=alco_dep_a['NUMDRIMO_EST'].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p1=alco_dep_a['NUMDRIMO_EST'].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c1,' ':' ', 'Percent':p1})
print(ferq_table)
IDNUM S2AQ8A USFREQMO NUMDRIMO_EST
Frequency and precentages for the NUMDRIMO_EST
Frequency Percent
7.0 436 13.74%
8.0 221 6.97%
9.0 161 5.07%
10.0 53 1.67%
15.0 660 20.8%
20.0 475 14.97%
25.0 528 16.64%
30.0 134 4.22%
42.0 360 11.35%
44.0 128 4.03%
NaN 17 0.54%
we notice that most adults(20.8%) drink 15 drinks per month
4- Divide the AGE variable to 3 groups:18-20,21-22,23-25:
# categorize quantitative variable based on customized splits using cut function
# splits into 3 groups (18-20, 21-22, 23-25)
print ('AGE - 3 categories - quartiles')
alco_dep_a['AGEGROUP3']=pd.cut(alco_dep_a.AGE,[17,20,22,25])
c=alco_dep_a['AGEGROUP3'].value_counts(sort=False, dropna=True)
print(c)
#crosstabs evaluating which ages were put into which AGEGROUP3
print('crosstabs evaluating which ages were put into which AGEGROUP3:')
print (pd.crosstab(alco_dep_a['AGEGROUP3'],alco_dep_a['AGE']))
#frequency distribution for AGEGROUP3
print('frequency distribution and percentages for AGEGROUP3')
c=alco_dep_a['AGEGROUP3'].value_counts(sort=False, dropna=True)
p=alco_dep_a['AGEGROUP3'].value_counts(sort=False,normalize=True,dropna=True).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c,' ':' ', 'Percent':p})
print(ferq_table)
AGE - 3 categories - quartiles
Name: AGEGROUP3, dtype: int64
crosstabs evaluating which ages were put into which AGEGROUP3:
AGE 18 19 20 21 22 23 24 25
(17, 20] 266 358 348 0 0 0 0 0
(20, 22] 0 0 0 453 436 0 0 0
(22, 25] 0 0 0 0 0 443 471 398
frequency distribution and percentages for AGEGROUP3
From this table we notice that most adults 41.35% in the third group (22-25).
Summary of Frequency Distributions:
for variable S2AQ8A I created a secondary NUMDRIMO_EST variable to compute number of drinks each participant consumes per month.
To achieve this, I re-coded this variable from 1-6 as below:
2- Nearly every day (5-6 times a week)
4- Once to 2 times a week
I think this coding is better and more accurate because a person cannot remember exactly what he consumed if the period become more than month.
we notice from the results above that most adults (20.8%) drink 15 drinks per month(variable NUMDRIMO_EST).
- from the age groups we notice from the results above that most adults(41.35%) falls in the group 22-25).
Appendix:(full python code):
#import pandas,Numpy library
import pandas as pd
import numpy
data=pd.read_csv('nesarc_pds.csv',low_memory=False,encoding='utf-8',na_values=' ')
print('number of rows:')
print(len(data)) # number of rows
print('number of variables (columns):')
print(len(data.columns)) # number of variables (columns)
#counts and percentages (i.e. frequency distributions) for each variable
alco_vars=['CONSUMER','S2AQ1','S2AQ2','S2AQ3','S2AQ8A','S2AQ8B']
for var in alco_vars:
data[var]=pd.to_numeric(data[var],errors='coerce')
#Recover valid data for the observations who answer no for the question Drank at least 12 alcoholic drink in last 12 months?
#set valid data for the variable S2AQ8A to dummy value 11
data.loc[(data[alco_vars[3]]!=9) &(data[alco_vars[4]].isnull()),alco_vars[4]]=11
#set valid data for the variable S2AQ8B to dummy value 100
data.loc[(data[alco_vars[3]]!=9) &(data[alco_vars[5]].isnull()),alco_vars[5]]=100
if var==alco_vars[0]:
print("{}-Drinking status,Current drinker=1, EX-drinker=2, Lifetime Abstainer=3".format(var))
elif var==alco_vars[1] :
print("{}-Drank at least 1 alcoholic drink in life ,yes=1, No=2".format(var))
elif var==alco_vars[2]:
print("{}-Drank at least 12 alcoholic drinks in last 12 months ,yes=1, No=2,Unknown=9".format(var))
elif var==alco_vars[3]:
print("{}-Drank at least 1 alcoholic drink in last 12 months ,yes=1, No=2,Unknown=9".format(var))
elif var==alco_vars[4]:
print("{}-How often drank any alcohol in last 12 months".format(var))
else:
print("{}- drinks of any alcohol consumed on days when drank alcohol in last 12 months ".format(var))
c = data[var].value_counts(sort=False,dropna=False).sort_index(ascending=False)
p=data[ var].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=True).astype(float).mul(100).round(2).astype(str)+'%'
ferq_table=pd.DataFrame({'Frequency':c,' ':' ', 'Percent':p})
##subset data to young adults age 18 to 25 who have drank at least 12 alcoholic drink in the last 12 months
sub1=data[(data['AGE']>=18) & (data['AGE']<=25) & (data['S2AQ2']==1)]
#make a copy of new subsetted data
alco_dep_a =sub1.copy()
# frequency distritions on new alco_dep_a data frame
print("Frequency and percentages for subset data( young adults age 18 to 25 who have drank at least 12 alcoholic drink in the last 12 months):")
alco_a_vars=['AGE','S2AQ2','S2AQ8A','S2AQ8B']
if var==alco_a_vars[0]:
print("adults age 18-25 by-{} tab".format(var))
elif var==alco_a_vars[1]:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{} adults who drank at least 12 alcoholic drink in the last 12 months".format(var))
elif var==alco_a_vars[2]:
#recode 99 values as missing for the variable S2AQ8A:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{}- How often drank any alcohol in last 12 months".format(var))
else:
#recode 99 values as missing for the variable S2AQ8B:
alco_dep_a[var]=alco_dep_a[var].replace(99,numpy.nan)
print("{}-Number of drinks of any alcohol consumed on days when drank alcohol in last 12 months".format(var))
c=alco_dep_a[var].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p=alco_dep_a[var].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=True).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c,' ':' ', 'Percent':p})
print(ferq_table)
#recording values for S2AQ8A and create new variables
#recoding values for S2AQ8A into a new variable, USFREQ the new code from 1-6
print('recoding values for S2AQ8A-How often drank alcohol in last 12 months?- in to a new variable,USFREQ ,the new code from 1-6')
recode1 = {1:1,2:2,3:3,4:4,5:4,6:5,7:6,8:6,9:6,10:6}
alco_dep_a['USFREQ']= alco_dep_a['S2AQ8A'].map(recode1)
c1=alco_dep_a['USFREQ'].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p1=alco_dep_a['USFREQ'].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c1,' ':' ', 'Percent':p1})
print(ferq_table)
#reverse the code values to indicate high frequency values in the first and low frequency values in the last
print('reverse the code values to indicate high frequency take high values and low frequency take low values ')
#recoding values for S2AQ8A into a new variable, USFREQ1
recode2 = {1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1}
alco_dep_a['USFREQ1']= alco_dep_a['USFREQ'].map(recode2)
print(alco_dep_a['USFREQ1'].value_counts(sort=False,dropna=False).sort_index(ascending=True))
#recoding values for S2AQ8A into a new variable, USFREQMO
print('Create secondary variable USFREQMO to indicate how often you drank last 12 months as quantitative value per month')
recode3= {1: 30, 2: 22, 3: 14, 4: 5, 5: 2.5, 6: 1}
alco_dep_a['USFREQMO']= alco_dep_a['USFREQ'].map(recode3)
c1=alco_dep_a['USFREQMO'].value_counts(sort=False,dropna=False).sort_index(ascending=True)
p1=alco_dep_a['USFREQMO'].value_counts(sort=False,normalize=True,dropna=False).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c1,' ':' ', 'Percent':p1})
print(ferq_table)
#secondary variable multiplying the number of days drank/month and the approx number of drinks drank/day
alco_dep_a['NUMDRIMO_EST']=alco_dep_a['USFREQMO'] * alco_dep_a['S2AQ8A']
sub3=alco_dep_a[['IDNUM','S2AQ8A','USFREQMO','NUMDRIMO_EST']]
print(sub3.head(25))
# categorize quantitative variable based on customized splits using cut function
# splits into 3 groups (18-20, 21-22, 23-25)
print ('AGE - 3 categories - quartiles')
alco_dep_a['AGEGROUP3']=pd.cut(alco_dep_a.AGE,[17,20,22,25])
c=alco_dep_a['AGEGROUP3'].value_counts(sort=False, dropna=True)
print(c)
#crosstabs evaluating which ages were put into which AGEGROUP3
print('crosstabs evaluating which ages were put into which AGEGROUP3:')
print (pd.crosstab(alco_dep_a['AGEGROUP3'],alco_dep_a['AGE']))
#frequency distribution for AGEGROUP3
print('frequency distribution and percentages for AGEGROUP3')
c=alco_dep_a['AGEGROUP3'].value_counts(sort=False, dropna=True)
p=alco_dep_a['AGEGROUP3'].value_counts(sort=False,normalize=True,dropna=True).sort_index(ascending=False).mul(100).round(2).astype(str) + '%'
ferq_table=pd.DataFrame({'Frequency':c,' ':' ', 'Percent':p})
print(ferq_table)
#upper-case all DataFrame column names - place afer code for loading data aboave
data.columns = map(str.upper, data.columns)
# bug fix for display formats to avoid run time errors - put after code for loading data above
pd.set_option('display.float_format', lambda x:'%f'%x