Python in Excel
Una tecnica avanzata per eseguire analisi dati
Come Integrare Python in Excel
Introduzione
L'integrazione di Python in Excel permette di eseguire analisi dati avanzate, automazioni e manipolazioni dei fogli di calcolo. Con strumenti come Python in Excel (Microsoft 365), xlwings e pandas, è possibile scrivere ed eseguire codice direttamente in Excel.
Perché Usare Python in Excel?
I vantaggi principali dell'integrazione di Python in Excel sono:
- ✔ Maggiore potenza di calcolo con librerie avanzate.
- ✔ Automazione senza VBA.
- ✔ Compatibilità con Windows e Mac.
Come Usare Python in Excel
Metodo 1: Usare Python in Excel (Microsoft 365)
Microsoft Excel supporta nativamente Python nelle celle. Per eseguire codice, scrivi:
=PY("import pandas as pd;df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]}); df")
Esempio di Regressione Lineare
=PY("import numpy as np; import pandas as pd; from sklearn.linear_model import LinearRegression; X = np.array([1,2,3,4,5]).reshape(-1,1); Y = np.array([2,3,5,7,11]); model = LinearRegression().fit(X,Y); model.predict([[6]])")
Metodo 2: Usare xlwings per Python in Excel
Installare xlwings
Per collegare Excel a Python, installa xlwings:
pip install xlwings
Scrivere Dati in Excel con Python
import xlwings as xw
# Apri Excel
wb = xw.Book()
sheet = wb.sheets.active
# Scrivi dati
sheet["A1"].value = "Categoria"
sheet["B1"].value = "Vendite"
sheet["A2"].value = "Elettronica"
sheet["B2"].value = 5000
# Salva il file
wb.save("output.xlsx")
print("Dati salvati in Excel!")
Collegare Excel a Python
In Excel, vai su Sviluppo > Macro > xlwings RunPython e scrivi:
Sub EseguiPython()
RunPython "import script_python; script_python.main()"
End Sub
Esempio: Regressione Lineare in Excel con Python
Vogliamo prevedere le vendite per un budget di 3000$ usando Python:
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# Carica i dati
dati = pd.DataFrame({
"Budget": [500, 1000, 1500, 2000, 2500],
"Vendite": [10, 20, 28, 35, 45]
})
# Modello di regressione lineare
X = dati["Budget"].values.reshape(-1, 1)
Y = dati["Vendite"].values
model = LinearRegression().fit(X, Y)
# Previsione per 3000$
vendite_predette = model.predict([[3000]])
# Scrive il risultato in Excel
wb = xw.Book()
sheet = wb.sheets.active
sheet["A1"].value = "Previsione Vendite per 3000$"
sheet["B1"].value = vendite_predette[0]
print("Previsione completata!")
Conclusione
- ✔ Python in Excel è disponibile su Microsoft 365.
- ✔ xlwings permette di usare Python in Excel su Windows e Mac.
- ✔ Python è utile per analisi avanzate e automazioni.