Q011 - Quali altre attività condividono la sede 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]:
1# Range: D11[SQ001] - D10[SQ005] - D11[other]

activity_columns = ["D11[SQ001]","D11[SQ002]","D11[SQ003]","D11[SQ004]","D11[SQ005]"]
activity_options = ['Coworking',
               'Botteghe artigiane',
               'Studi di progettazione',
               'Studi di prototipazione',
               'Servizi di produzione']
activity = data[activity_columns]
activity.replace(u'Sì', 'Si', inplace=True) # Get rid of accented characters 
activity_other = data['D11[other]'].str.lower().value_counts()


-c:10: 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]:
#places[0:4]

Combinations...


In [6]:
# Create all the possible combinations from the main options
# See http://stackoverflow.com/questions/17176887/python-get-all-permutation-of-a-list-w-o-repetitions

import itertools 

all_combinations = {}
all_combinations_columns = []

for i in range(1, len(activity_columns)+1):
    comb = list(itertools.combinations(activity_columns, i))
    for k in comb:
        # Each combination
        all_combinations[k] = {}
        all_combinations[k]["col_list"] = list(k)
        # Build the string and boolean list of each combination
        comb_list = []
        comb_bool_list = []
        # Put default False value
        for l in activity_columns:
            comb_bool_list.append(False)
        for j in k:
            pos = activity_columns.index(j) # Get position
            comb_list.append(activity_options[pos])
            comb_bool_list[pos] = True
        all_combinations[k]["list"] = comb_list
        all_combinations[k]["bool_list"] = comb_bool_list
        all_combinations[k]["str"] = ", ".join(comb_list)

In [7]:
# Check which combinations correspond each row
str_values = []
for i in activity.index:
    current_bool_list = list(activity.ix[i].isin(["Si"]))
    for i in all_combinations:
        if current_bool_list == all_combinations[i]["bool_list"]:
            str_values.append(all_combinations[i]["str"])

In [8]:
# Add combination column
activity["Combination"] = pd.Series(str_values)


-c:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

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

In [9]:
# Gather data
resulting_combinations = activity["Combination"].value_counts()
resulting_combinations_percentage = activity["Combination"].value_counts(normalize=True)*100

In [10]:
# Plotting the first 10 values of the most popular combinations
resulting_combinations[0:10].plot(kind='bar',figsize=(20,10),rot=90)
plt.title(u"Quali altre attività condividono la sede del laboratorio?", fontsize=18, y=1.02)
plt.ylabel("Lab", fontsize=16)
plt.xlabel("Combinazioni", fontsize=16)
plt.savefig("svg/Q011-Combinazioni.svg")
plt.savefig("png/Q011-Combinazioni.png")
plt.savefig("pdf/Q011-Combinazioni.pdf")



In [11]:
%%capture output

# Save the output as a variable that can be saved to a file
# Data of the combinations
print "Data:"
print resulting_combinations
print
# Data of the combinations: percentage
print "Data %:"
print resulting_combinations_percentage

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


The following commands were written to file `Q011-Combinazioni.py`:
Data:
Coworking                                                       9
Studi di prototipazione                                         5
Studi di progettazione, Studi di prototipazione                 4
Coworking, Botteghe artigiane, Studi di progettazione, Studi di prototipazione, Servizi di produzione    4
Coworking, Studi di prototipazione                              3
Botteghe artigiane                                              3
Coworking, Studi di progettazione, Studi di prototipazione      3
Coworking, Studi di prototipazione, Servizi di produzione       2
Studi di progettazione                                          2
Coworking, Studi di progettazione                               2
Studi di progettazione, Studi di prototipazione, Servizi di produzione    2
Coworking, Botteghe artigiane, Studi di progettazione, Studi di prototipazione    2
Servizi di produzione                                           2
Studi di progettazione, Servizi di produzione                   1
Botteghe artigiane, Studi di prototipazione                     1
Botteghe artigiane, Studi di progettazione, Studi di prototipazione, Servizi di produzione    1
Botteghe artigiane, Studi di progettazione, Studi di prototipazione    1
Botteghe artigiane, Servizi di produzione                       1
Coworking, Botteghe artigiane, Studi di progettazione           1
dtype: int64

Data %:
Coworking                                                       12.857143
Studi di prototipazione                                          7.142857
Studi di progettazione, Studi di prototipazione                  5.714286
Coworking, Botteghe artigiane, Studi di progettazione, Studi di prototipazione, Servizi di produzione     5.714286
Coworking, Studi di prototipazione                               4.285714
Botteghe artigiane                                               4.285714
Coworking, Studi di progettazione, Studi di prototipazione       4.285714
Coworking, Studi di prototipazione, Servizi di produzione        2.857143
Studi di progettazione                                           2.857143
Coworking, Studi di progettazione                                2.857143
Studi di progettazione, Studi di prototipazione, Servizi di produzione     2.857143
Coworking, Botteghe artigiane, Studi di progettazione, Studi di prototipazione     2.857143
Servizi di produzione                                            2.857143
Studi di progettazione, Servizi di produzione                    1.428571
Botteghe artigiane, Studi di prototipazione                      1.428571
Botteghe artigiane, Studi di progettazione, Studi di prototipazione, Servizi di produzione     1.428571
Botteghe artigiane, Studi di progettazione, Studi di prototipazione     1.428571
Botteghe artigiane, Servizi di produzione                        1.428571
Coworking, Botteghe artigiane, Studi di progettazione            1.428571
dtype: float64