# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3.9.7 ('base')
#     language: python
#     name: python3
# ---

# # Set e Fronzenset

# - Set: sequenza mutabile
# - Fronzenset: sequenza immutabile

{1, 2, 3, 2, 1} # sequenza ove gli elementi devono essere univoci

set('abracadabra')

frozenset('abracadabra')

# +
# Tra tutte i metodi di set solo copy() è supportato da fronzenset, dato che gli altri metodi mutano il set
# -

# # Grafici
#
# ```python
# pip install pygal
# ```

# +
import pygal

def draw_xy(title, xvals, yvals):
    """
    Draw xy plot with given x and y values.
    """
    coords = [(xval, yval) for xval, yval in zip(xvals, yvals)]
    xyplot = pygal.XY(height=400)
    xyplot.title = title
    xyplot.add("Data", coords)
    xyplot.render_in_browser()

xvals = [0, 1, 3, 5, 6, 7, 9, 11, 12, 15]
yvals = [4, 3, 1, 2, 2, 4, 5, 2, 1, 4]

draw_xy("My XY Plot", xvals, yvals)

# -

# ## matplotlib (recommended)
#
# ```python
# import matplotlib.pyplot as plt
# ```
#
# Raccolta di funzioni che fanno funzionare matplotlib come MATLAB

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

# Se matplotlib fosse limitato a lavorare con gli elenchi, sarebbe abbastanza inutile per l'elaborazione numerica. 
# Generalmente, si usano array numpy. 
# In effetti, tutte le sequenze vengono convertite internamente in array numpy.
#
# ```python
# import numpy as np
# import matplotlib.pyplot as plt
# ```

# # Pandas
#
# La libreria Pandas viene utilizzata per analisi dei dati.
#
# ```python
# from pandas import DataFrame, read_csv
# import matplotlib.pyplot as plt
# import pandas as pd
# ```

# +
# Il set di dati consisterà in 5 nomi di bambini e il numero di nascite registrate per quell'anno (1880).

names = ['Bob','Jessica','Mary','John','Mel']
births = [968, 155, 77, 578, 973]

# Per unire questi due elenchi insieme useremo la funzione zip.

BabyDataSet = list(zip(names,births))
print(BabyDataSet)

# -

# ---

# +
import pandas as pd
from numpy import random

names = ['Bob','Jessica','Mary','John','Mel']

random.seed(500)
random_names = [names[random.randint(low=0,high=len(names))] for i in range(1000)]

print(random_names[:10])

births = [random.randint(low=0,high=1000) for i in range(1000)]
print(births[:10])

BabyDataSet = list(zip(random_names,births))
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
print(df[:10])

df['Names'].unique()

for x in df['Names'].unique():
    print(x)

print(df['Names'].describe())

name = df.groupby('Names')

df = name.sum()
print(df)

Sorted = df.sort_values(['Births'], ascending=False)
print(Sorted)
print(Sorted.head(1))

df['Births'].plot.bar()

# -

# ---

# +
import pandas as pd

d = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

df = pd.DataFrame(data=d, columns=['Numbers'])

print(df)
# -

df['Numbers'] = df['Numbers'] + 1
print(df)

# ---

# +
import pandas as pd

d = {'one':[1,1],'two':[2,2]}
i = ['a','b']

# Create dataframe
df = pd.DataFrame(data = d, index = i)
print(df)

print(df.index)
# -

stack = df.stack()
print(stack)
print(stack.index) # Doppia indicizzazione

transpose = df.T
print(transpose)

# ---

import pandas as pd
d = {'one':[1,1,1,1,1],
     'two':[2,2,2,2,2],
     'letter':['a','a', 'b', 'b', 'c']}
df = pd.DataFrame(d)
print(df)

one = df.groupby('letter')
print(one.sum())

letterone = df.groupby(['letter','one']).sum()
print(letterone)
print(letterone.index)

letterone = df.groupby(['letter','one'], as_index=False).sum()
print(letterone)

# # Animazioni
#
# Esistono due modi per creare animazioni utilizzando  Matplotlib: 
# - Utilizzo della funzione pause() 
# - Utilizzo della funzione FuncAnimation() 

# ## Pause()

# +
from matplotlib import pyplot as plt
  
x = []
y = []
  
for i in range(100):
    x.append(i)
    y.append(i)
  
    plt.xlim(0, 100)
    plt.ylim(0, 100)
      
    
    plt.plot(x, y, color = 'green')
    plt.pause(0.01)
  
plt.show() # visualizzazione non è ottimale su Jupyter Notebook
# -

# ## FuncAnimation()

# +
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
  
x = []
y = []
figure, ax = plt.subplots()
  
# Setting limits for x and y axis
ax.set_xlim(0, 100)
ax.set_ylim(0, 12)
  
# Since plotting a single graph
line,  = ax.plot(0, 0) 
  
def animation_function(i):
    x.append(i * 15)
    y.append(i)  
    line.set_xdata(x)
    line.set_ydata(y)
    return line,
  
animation = FuncAnimation(figure, func = animation_function, frames = np.arange(0, 10, 0.1), interval = 10)
plt.show()


StarcoderdataJupyterScriptsDedupFiltered