2015-04-30 9 views
5

Sto provando a scrivere un panda DataFrame in un file .xlsx in cui diverse colonne numeriche avrebbero formati diversi. Ad esempio, alcuni mostrerebbero solo due cifre decimali, alcuni non mostrerebbero nessuno, alcuni sarebbero formattati come percentuali con un simbolo "%", ecc.Scrittura di pandi DataFrame in Excel con diversi formati per diverse colonne

Ho notato che DataFrame.to_html() ha un parametro formatters che consente di fare proprio questo , mappando diversi formati a diverse colonne. Tuttavia, non esiste un parametro simile nel metodo DataFrame.to_excel(). Il massimo che abbiamo è un float_format globale per tutti i numeri.

Ho letto molti SO messaggi che sono almeno in parte legati alla mia domanda, per esempio:

Ci sono altri più conveniente funzioni di Excel correlate/proprietà nella API di panda che possono aiutare qui, o qualcosa di simile su openpyxl, o forse qualche modo per specificare il formato di output metadati direttamente su ogni colonna nello DataFrame che sarebbero poi interpretati a valle da diversi outputter?

+0

E la rimozione di TUTTI i formati? Qualcuno sa se c'è un modo rapido per farlo? – Lisle

risposta

9

Si può fare questo con i panda 0,16 e il motore XlsxWriter accedendo la cartella di lavoro e del foglio di lavoro oggetti sottostanti:

import pandas as pd 

# Create a Pandas dataframe from some data. 
df = pd.DataFrame(zip(
    [1010, 2020, 3030, 2020, 1515, 3030, 4545], 
    [.1, .2, .33, .25, .5, .75, .45], 
    [.1, .2, .33, .25, .5, .75, .45], 
)) 

# Create a Pandas Excel writer using XlsxWriter as the engine. 
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') 
df.to_excel(writer, sheet_name='Sheet1') 

# Get the xlsxwriter objects from the dataframe writer object. 
workbook = writer.book 
worksheet = writer.sheets['Sheet1'] 

# Add some cell formats. 
format1 = workbook.add_format({'num_format': '#,##0.00'}) 
format2 = workbook.add_format({'num_format': '0%'}) 
format3 = workbook.add_format({'num_format': 'h:mm:ss AM/PM'}) 

# Set the column width and format. 
worksheet.set_column('B:B', 18, format1) 

# Set the format but not the column width. 
worksheet.set_column('C:C', None, format2) 

worksheet.set_column('D:D', 16, format3) 

# Close the Pandas Excel writer and output the Excel file. 
writer.save() 

uscita:

enter image description here

Vedi anche Working with Python Pandas and XlsxWriter.

3

Come giustamente rilevare l'applicazione di formati a singole celle è estremamente inefficiente.

openpyxl 2.4 include il supporto nativo per i datagrammi Pandas e gli stili con nome.

Problemi correlati