#!/usr/bin/env python # coding: utf-8 # # 19 Tableaux et analyse de données # ### 19.1 Tableau unidimensionnel de données # In[2]: from sympy import isprime L = [i for i in range(100) if isprime(i)] L # In[3]: from pandas import Series s = Series(L) s # In[4]: s[13] # In[7]: s.argmax() # In[8]: s.cumsum() # ### 19.2 Afficher quelques statistiques # In[9]: s.describe() # In[10]: s.mean() # In[11]: s.std() # In[12]: s.min() # In[13]: def f(p): return p**2 - 3 s.apply(f) # ### 19.3 Opérations sur une série # In[16]: s * 10000 + 45 # In[17]: s / sum(s) # In[18]: t = Series([i**3 for i in range(25)]) # In[19]: t # In[22]: s ** t # ### 19.4 Concaténation de deux séries # In[25]: from pandas import concat df = concat([s,t], axis=1) df # In[26]: type(df) # ### 19.5 Tableau 2-dimensionnel de données # In[34]: import pandas as pa d = {'nb premiers':s, 'cubes':t} df = pa.DataFrame(d, columns=['nb premiers', 'cubes']) # In[35]: df # In[37]: df.describe() # ### 19.6 Accéder à une colonne d'un tableau # In[36]: df['cubes'] # ### 19.7 Afficher les premières/dernières lignes # In[38]: L = [isprime(i) for i in range(10000)] # In[39]: L[:10] # In[40]: L = map(isprime, range(10000)) # In[43]: L[:10] # In[44]: s = Series(L) # In[45]: t = s.cumsum() # In[49]: df = pa.DataFrame() # In[50]: df['isprime'] = s # In[51]: df['pi_x'] = t # In[53]: df.head() # In[55]: df.tail(8) # ### 19.8 Sous-tableau # In[56]: df[500:520] # ### 19.9 Ajouter une colonne dans un tableau # In[57]: from math import log # In[58]: 10000 / log(10000) # In[62]: from math import sqrt 12.29*sqrt(10000) # In[63]: def x_sur_log_x(x): if x > 1: return x/log(x) else: return None # In[64]: X = Series(range(10000)) gauss = X.apply(x_sur_log_x) nous = X.apply(lambda x:12.29*sqrt(x)) # In[65]: df['x_logx'] = gauss df['nous'] = nous # In[66]: df.head() # ### 19.10 Visualiser les données # In[67]: get_ipython().run_line_magic('matplotlib', 'inline') # In[68]: df.plot() # In[70]: del df['nous'] df[:100].plot() # In[79]: from sympy import Li df['Li_x'] = Series([Li(x).n() for x in range(10000)], dtype='float64') # In[80]: df.head() # In[81]: df.Li_x # In[84]: df.plot() # ### 19.11 Exporter des données # In[85]: from pandas import ExcelWriter writer = ExcelWriter('tableau.xlsx') df.to_excel(writer, 'Feuille 1') writer.save() # In[87]: df.to_csv('tableau.csv') # In[88]: ls # In[89]: get_ipython().system('head tableau.csv') # ### 19.12 Importer des données # In[91]: df2 = pa.read_excel('tableau.xlsx') # In[92]: df2.head() # In[ ]: pa.read_csv # ### 19.13 Exemple: analyser des données de data.gov.be # In[ ]: