Q021 - Qual è la forma giuridica del laboratorio?


In [1]:
# -*- coding: UTF-8 -*-

# Render our plots inline
%matplotlib inline 

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn
import shutil

pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier, overridden by seaborn
pd.set_option('display.max_columns', None) # Display all the columns
plt.rcParams['font.family'] = 'sans-serif' # Sans Serif fonts for all the graphs

# Reference for color palettes: http://web.stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html

# Change the font
matplotlib.rcParams.update({'font.family': 'Source Sans Pro'})

In [2]:
# Load csv file first
data = pd.read_csv("data/lab-survey.csv", encoding="utf-8")

In [3]:
# Check data
#data[0:4] # Equals to data.head()

In [4]:
# Range: D21[SQ001] - D21[SQ008] - D21[other]

lab_columns = ['D21[SQ001]','D21[SQ002]','D21[SQ003]','D21[SQ004]','D21[SQ005]','D21[SQ006]','D21[SQ007]','D21[SQ008]']
lab_options = ['Nessuna formalizzazione',
               'Associazione di fatto',
               'Associazione registrata',
               'Fondazione',
               'Srl',
               'Cooperativa',
               u'Unità o dipartimento di ente',
               u'Unità o dipartimento di impresa']
lab = data[lab_columns]
lab.replace(u'Sì', 'Si', inplace=True) # Get rid of accented characters 
lab_other = data['D21[other]'].str.lower().value_counts()


-c:13: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [5]:
#lab[0:4]

In [6]:
%%capture output

# Save the output as a variable that can be saved to a file
# Gather data
lab_b = {}

for k,i in enumerate(lab_columns):
    lab_b[k] = lab[i].value_counts(dropna=False)
    print "Data:",lab_options[k].encode('utf-8')
    print lab_b[k]
    print
    print "Data %:",lab_options[k].encode('utf-8')
    print lab[i].value_counts(normalize=True,dropna=False)*100
    print

In [7]:
# Save+show the output to a text file
%save Q012-FormaGiuridica01.py str(output)
shutil.move("Q012-FormaGiuridica01.py", "text/Q012-FormaGiuridica01.txt")


The following commands were written to file `Q012-FormaGiuridica01.py`:
Data: Nessuna formalizzazione
No     54
Si     16
NaN     0
dtype: int64

Data %: Nessuna formalizzazione
No     77.142857
Si     22.857143
NaN     0.000000
dtype: float64

Data: Associazione di fatto
No     62
Si      8
NaN     0
dtype: int64

Data %: Associazione di fatto
No     88.571429
Si     11.428571
NaN     0.000000
dtype: float64

Data: Associazione registrata
No     44
Si     26
NaN     0
dtype: int64

Data %: Associazione registrata
No     62.857143
Si     37.142857
NaN     0.000000
dtype: float64

Data: Fondazione
No     69
Si      1
NaN     0
dtype: int64

Data %: Fondazione
No     98.571429
Si      1.428571
NaN     0.000000
dtype: float64

Data: Srl
No     61
Si      9
NaN     0
dtype: int64

Data %: Srl
No     87.142857
Si     12.857143
NaN     0.000000
dtype: float64

Data: Cooperativa
No     68
Si      2
NaN     0
dtype: int64

Data %: Cooperativa
No     97.142857
Si      2.857143
NaN     0.000000
dtype: float64

Data: Unità o dipartimento di ente
No     64
Si      6
NaN     0
dtype: int64

Data %: Unità o dipartimento di ente
No     91.428571
Si      8.571429
NaN     0.000000
dtype: float64

Data: Unità o dipartimento di impresa
No     69
Si      1
NaN     0
dtype: int64

Data %: Unità o dipartimento di impresa
No     98.571429
Si      1.428571
NaN     0.000000
dtype: float64



In [8]:
yes = []
no = []
nanvalue = []

for k,i in enumerate(lab_columns):
    lab_presents = lab_b[k].index.tolist()
    
    # Convert NaN to "NaN"
    for o,h in enumerate(lab_presents):
        if type(h) is float:
            lab_presents.pop(o)
            lab_presents.append("NaN")
    
    # Reassign new list with "NaN"
    lab_b[k].index = lab_presents
    
    # Check for empty values, and put a 0 instead
    if "Si" not in lab_presents:
        yes.append(0)
    if "No" not in lab_presents:
        no.append(0)
    if "NaN" not in lab_presents:
        nanvalue.append(0)
    
    for j in lab_presents:
        if j == "Si":
            yes.append(lab_b[k].ix["Si"])
        elif j == "No":
            no.append(lab_b[k].ix["No"])
        elif j == "NaN":
            nanvalue.append(lab_b[k].ix["NaN"])

In [9]:
# Plot the data
plt.figure(figsize=(8,6))
plt.xlabel(u'Forma giuridica', fontsize=16)
plt.ylabel(u'Lab', fontsize=16)
plt.title(u'Qual è la forma giuridica del laboratorio?', fontsize=18, y=1.02)
plt.xticks(range(len(lab_options)),lab_options,rotation=90)
ind = np.arange(len(lab_columns))   # the x locations for the groups
width = 0.25                              # the width of the bars

my_colors = seaborn.color_palette("Set1", 3) # Set color palette
rect1 = plt.bar(ind,yes,width,color=my_colors[1],align='center') # Plot Yes
rect2 = plt.bar(ind+width,no,width,color=my_colors[0],align='center') # Plot No 
rect3 = plt.bar(ind+width*2,nanvalue,width,color=my_colors[2],align='center') # Plot NaN 
plt.legend( (rect1, rect2, rect3), ('Si', 'No', 'Nessuna risposta') )
plt.savefig("svg/Q012-FormaGiuridica01.svg")
plt.savefig("png/Q012-FormaGiuridica01.png")
plt.savefig("pdf/Q012-FormaGiuridica01.pdf")



In [10]:
%%capture output

# Save the output as a variable that can be saved to a file
# Get "other" data
lab_other = data["D21[other]"].str.lower().value_counts()
print "Data:"
print lab_other
print ""
print "Data %:"
print data["D21[other]"].str.lower().value_counts(normalize=True) * 100

In [11]:
# Save+show the output to a text file
%save Q012-FormaGiuridica02.py str(output)
shutil.move("Q012-FormaGiuridica02.py", "text/Q012-FormaGiuridica02.txt")


The following commands were written to file `Q012-FormaGiuridica02.py`:
Data:
laboratorio rei                                                 1
liberi professionisti a p.iva sotto lo stesso marchio registrato    1
in corso di registrazione formale                               1
é gestito dalla cooperativa                                     1
poggia sulla mia ditta individuale                              1
associazione + ditta individuale studio professionale           1
s.                                                              1
un'iniziativa di una ditta individuale                          1
srls                                                            1
associazione non riconosciuta                                   1
associazione di promozione sociale                              1
ats o ati                                                       1
srl semplificata                                                1
ditta individuale                                               1
ass. no profit                                                  1
stiamo per fare un'associazione                                 1
dtype: int64

Data %:
laboratorio rei                                                 1.428571
liberi professionisti a p.iva sotto lo stesso marchio registrato    1.428571
in corso di registrazione formale                               1.428571
é gestito dalla cooperativa                                     1.428571
poggia sulla mia ditta individuale                              1.428571
associazione + ditta individuale studio professionale           1.428571
s.                                                              1.428571
un'iniziativa di una ditta individuale                          1.428571
srls                                                            1.428571
associazione non riconosciuta                                   1.428571
associazione di promozione sociale                              1.428571
ats o ati                                                       1.428571
srl semplificata                                                1.428571
ditta individuale                                               1.428571
ass. no profit                                                  1.428571
stiamo per fare un'associazione                                 1.428571
dtype: float64


In [12]:
# Plot bar
plt.figure(figsize=(8,6))
plt.title(u'Qual è la forma giuridica del laboratorio? Altro', fontsize=18, y=1.02)
plt.xticks(range(len(lab_other.index)),lab_other.index,rotation=90)
plt.xlabel('Forma Giuridica', fontsize=16)
plt.ylabel('Lab', fontsize=16)
ind = np.arange(len(lab_other))   # the x locations for the groups
width = 0.35                       # the width of the bars

my_colors = seaborn.color_palette("husl", len(lab_other)) # Set color palette
rect1 = plt.bar(ind,lab_other,width,color=my_colors,align='center')
plt.savefig("svg/Q021-FormaGiuridicaAltro02.svg")
plt.savefig("png/Q021-FormaGiuridicaAltro02.png")
plt.savefig("pdf/Q021-FormaGiuridicaAltro02.pdf")



In [12]: