2016-04-19 9 views
9

Sto provando a scindere i singoli dataframes da un groupby per stamparli come tabelle HTML pandas. Ho bisogno di fare riferimento e renderli individualmente come tabelle in modo da poterli screenshot per una presentazione.Panda: come fare riferimento e stampare più dataframes come tabelle HTML

Questo è il mio codice corrente:

import pandas as pd 

df = pd.DataFrame(
    {'area': [5, 42, 20, 20, 43, 78, 89, 30, 46, 78], 
    'cost': [52300, 52000, 25000, 61600, 43000, 23400, 52300, 62000, 62000, 73000], 
    'grade': [1, 3, 2, 1, 2, 2, 2, 4, 1, 2], 'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005], 
    'team': ['man utd', 'chelsea', 'arsenal', 'man utd', 'man utd', 'arsenal', 'man utd', 'chelsea', 'arsenal', 'arsenal']}) 

result = df.groupby(['team', 'grade']).agg({'cost':'mean', 'area':'mean', 'size':'sum'}).rename(columns={'cost':'mean_cost', 'area':'mean_area'}) 

dfs = {team:grp.drop('team', axis=1) 
     for team, grp in result.reset_index().groupby('team')} 

for team, grp in dfs.items(): 
    print('{}:\n{}\n'.format(team, gap)) 

che stampa (come le tabelle non HTML):

chelsea: 
    grade mean_cost mean_area size 
2  3  52000   42 957 
3  4  62000   30 849 

arsenal: 
    grade  mean_cost mean_area size 
0  1 62000.000000 46.000000 973 
1  2 40466.666667 58.666667 3110 

man utd: 
    grade mean_cost mean_area size 
4  1  56950  12.5 2445 
5  2  47650  66.0 2579 

E 'possibile ottenere questi dataframes uno per uno come tabelle HTML? A scanso di equivoci, non ho bisogno di un metodo iterativo per restituirli tutti come tabelle HTML in una volta sola: sono felice di fare riferimento a ciascuna di esse individualmente.

risposta

8

Come Thomas K points out, si potrebbe usare IPython.core.display.display per incorporare la visualizzazione delle DataFrames insieme con le dichiarazioni di stampa in un notebook IPython:

import pandas as pd 
from IPython.core import display as ICD 


df = pd.DataFrame(
    {'area': [5, 42, 20, 20, 43, 78, 89, 30, 46, 78], 
    'cost': [52300, 52000, 25000, 61600, 43000, 23400, 52300, 62000, 62000, 73000], 
    'grade': [1, 3, 2, 1, 2, 2, 2, 4, 1, 2], 'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005], 
    'team': ['man utd', 'chelsea', 'arsenal', 'man utd', 'man utd', 'arsenal', 'man utd', 'chelsea', 'arsenal', 'arsenal']}) 

result = df.groupby(['team', 'grade']).agg({'cost':'mean', 'area':'mean', 'size':'sum'}).rename(columns={'cost':'mean_cost', 'area':'mean_area'}) 

dfs = {team:grp.drop('team', axis=1) 
     for team, grp in result.reset_index().groupby('team')} 

for team, grp in dfs.items(): 
    print(team) 
    ICD.display(grp) 

genera
enter image description here

+2

In realtà hanno un passo inutile qui - si dovrebbe essere in grado di chiamare 'ICD.display (grp)' alla fine per visualizzare la ricca copia del dataframe. –

+1

@ThomasK: Grazie mille per il miglioramento! – unutbu

Problemi correlati