Tempo di lettura stimato: 4 minuti
Questa importazione non vi costerà nulla, tranne l'esecuzione di un po' di codice!
La necessità di avere produttivamente una soluzione all in one per gestire i vostri dati come il vostro codice è diventata più critica man mano che i volumi di dati diventano più grandi. Voi, come analisti di dati, avete quindi bisogno di inviare i vostri dati in un file excel? In precedenza avremmo pubblicato un video Come rimuovere i caratteri indesiderati, e qui ci basiamo su quel tema, collegandoci con Excel.
Due tecniche usate qui per raggiungere questo obiettivo sono XLSX writer spiegato, e Openpyxl spiegato.
Gli elementi che copriamo sono:
- Carica i dati da un frame di dati e li popola in un file excel.
- Rinominare un foglio.
- Creare un nuovo foglio e dargli un nome.
- Guardiamo le proprietà, ovvero cambiare il colore di una scheda in giallo.
- Potrebbe essere necessario mettere del testo in una cella del foglio, per fungere da intestazione o per mostrare di avere una cifra totale.
- E l'ultima funzionalità trattata in questo video è come copiare i dati da un foglio all'altro.
Ci sono diversi vantaggi nel mettere tutto il lavoro in anticipo a Python:
- I vantaggi della pulizia dei dati o del formato consentono di risparmiare tempo.
- Dopo aver ricevuto il documento, è possibile rivederlo rapidamente senza correggere gli errori nei dati.
- Se si distribuisce l'output a più persone, si ottiene rapidamente ciò che vogliono, senza intervento manuale dopo che la logica è stata completata.
Ho certamente beneficiato di questa pulizia dei dati e l'importazione nell'esercizio di excel, dato che i due sono combinati ora, rende il processo più efficiente.
Ricordatevi di iscrivervi al nostro canale se vi piace il lavoro che stiamo facendo, grazie!
Analisi dei dati Irlanda
Il codice usato in questo video è qui:
########## - Previous video - How to check for invlaid characters in your dataset ###########
###########################################################################################################
#######################This video - How to import data into Excel #########################################
#In Python 3, leading zeros(at the start of a sequence of numbers) are not allowed on numbers
#Numbers need to be put between "" to be looped through
import pandas as pd
#Create a dataset locally
data = {'Number': ["00&00$000", '111$11111','2222€2222','3333333*33','444444444£','555/55555','666666@666666'],
'Error' : ['0','0','0','0','0','0','0']}
#Create a dataframe and tell it where to get its values from
df = pd.DataFrame (data, columns = ['Number','Error'])
#Function to loop through the dataset and see if any of the list values below are found and replace them
def run(*l):
#This line extracts all the special characters into a new column
#Using regular expressions it finds values that should not appear
df['Error'] = df['Number'].str.extract('(\D+|^(0)$)')
#This line removes anything with a null value
df.dropna(subset=['Error'], inplace=True)
#This line reads in the list and assigns it a value i, to each element of the list.
#Each i value assigned also assigns an index number to the list value.
#The index value is then used to check whether the value associated with it is in the df['Number'] column
#and then replaces if found
for i in l:
df['Fix']= df['Number'].str.replace(i[0],"").str.replace(i[1],"").str.replace(i[2],"").str.replace(i[3],"") \
.str.replace(i[4],"").str.replace(i[5],"").str.replace(i[6],"")
print("Error list to check against")
print(i[0])
print(i[1])
print(i[2])
print(i[3])
print(i[4])
print(i[5])
print(i[6])
display(df)
#This is the list of errors you want to check for
l = ['$','*','€','&','£','/','@']
run(l)
import xlsxwriter
#### This is the start of the code to import the data to excel
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r"C://dataanalyticsireland/Python Code/youtube/codeused/files/exportxlsx.xlsx")
################ XlsxWriter can only create new files. It cannot read or modify existing files.#################
# Position the dataframes in the worksheet, and names the sheet Analysis
df.to_excel(writer, sheet_name='Analysis') # Default position, cell A1.
# Close the Pandas Excel writer and output the Excel file.
writer.save()
writer.close()
### Modify the exportxlsx.xlsx file created above through openpyxl ###
#Load xlsx file, and rename tab "Analysis" to "NewAnalysis"
from openpyxl import load_workbook
importwb = load_workbook("C://dataanalyticsireland/Python Code/youtube/codeused/files/exportxlsx.xlsx")
existing_sheet = importwb['Analysis']
#existing_sheet.title = 'NewAnalysis'
#Create new sheet on existing excel sheet, 1 signifies that it is to be created after the first sheet
#The first sheet been value 0
newsheet = importwb.create_sheet("Newsheet", 1) # insert after the first sheet as we know it already exists.
#Setting the tab colour of the newsheet to yellow
newsheet.sheet_properties.tabColor ='FFFF00'
#Putting text into a particular cell
newsheet['B3'] = "This is some text"
#Tell the code to go to the sheet we want to copy
#sourcesheet=importwb['NewAnalysis']
#Tell the code to copy the data to the newsheetcopy. It creates a new sheet and copies the data in.
#newsheetcopy=importwb.copy_worksheet(sourcesheet)
importwb.save("C://dataanalyticsireland/Python Code/youtube/codeused/files/exportxlsx.xlsx")
importwb.close()