Estás navegando por el archivo de tutorial python.

Limpieza y transformaciones de datos con Python II

- el julio 26, 2017 en Fuentes de datos, Guest posts, Tutoriales, Uncategorized

Desde Escuela de Datos, Sebastián Oliva, fellow 2017, enseña cómo usar la librería de Pandas, Numpy y Seaborn para Python para hacer manipulaciones, transformaciones y tablas dinámicas o pivotes. En este ejercicio vimos cómo hacer un stack, agrupaciones, e incluso cómo usar un hash para hacer anónimos algunos de nuestros datos sin perder granularidad.
Pues seguir el webinar del 26 de julio paso a paso en el cuaderno que compartimos contigo. También puedes consultar el cuaderno de trabajo de Sebastián aquí.

Estas son las librerías que usaremos y que es requerido importar para nuestro ejercicio.
In [1]:
import pandas as pd
import numpy as np
import seaborn
%pylab notebook

import hashlib
import humanhash

Tablas Pivote

Es muy común la agrupación de información en formato ‘stack’ donde tenemos filas de datos que demuestran una correlación entre dos sets de valores.

Las tablas pivote son una forma de re-ordenar los datos en una estructura tabular donde podemos agrupar los valores convirtiendo las tuplas entre valores numéricos.

En este caso de ejemplo, crearemos un dataset de prueba con la diversidad de restaurantes en varias ciudades centroamericanas. En esta vamos a comenzar a trabajar con dos columnas, una donde describe cada ciudad y la otra con la variedad de cocina disponible en cada una.

In [2]:
data_restaurantes = {
    'ciudades': ['Guatemala','Guatemala','Guatemala','Guatemala','Guatemala','Guatemala','San José','San José','San José','San José','San José','San Salvador','San Salvador','San Salvador'],
    'culinaria': ['Chapina','Chapina','China','Thai','Italiana','Chapina','Italiana','China','Tica','Chapina','Tica','Tica','Italiana','China']
}

restaurantes_dataframe_pares = pd.DataFrame(data_restaurantes)
restaurantes_dataframe_pares
Out[2]:
ciudades culinaria
0 Guatemala Chapina
1 Guatemala Chapina
2 Guatemala China
3 Guatemala Thai
4 Guatemala Italiana
5 Guatemala Chapina
6 San José Italiana
7 San José China
8 San José Tica
9 San José Chapina
10 San José Tica
11 San Salvador Tica
12 San Salvador Italiana
13 San Salvador China

Podemos ver entonces este listado de valores, tupla por tupla. Que tal si queremos contar la presencia de cada tipo de cocina en cada región. Probemos utilizando entonces el comando DataFrame.pivot_table de Pandas.

Este pide unos cuantos argumentos los que podemos ver en la documentación. Unos cuantos son obvios, como el definir las filas y columnas que esperamos de la tabla objetivo. Sin embargo, lo más notable es que ya que los tipos de datos que estamos utilizando no son numéricos, es necesario que definamos una funcion de agrupación que nos permita contar la cantidad de instancias de cada combinación.

In [3]:
def funcion_agrupacion(elemento):
    return True

agrupacion_culinaria = restaurantes_dataframe_pares.pivot_table(
    index=["ciudades"],
    columns="culinaria",
    aggfunc=funcion_agrupacion,
    fill_value=False)
agrupacion_culinaria
Out[3]:
culinaria Chapina China Italiana Thai Tica
ciudades
Guatemala True True True True False
San José True True True False True
San Salvador False True True False True

Hmm, esto ya se ve con la forma que queremos, sin embargo solo nos muestra la presencia o ausencia de algún tipo de cocina. Esto es fácil de explicar ya que definimos nuestra función de agrupación como retornar True si existe presencia a retornar False si No. ¿Qué tal si hacemos una mejor función de agrupación?

In [4]:
def funcion_agrupacion(elemento):
    '''Contemos cuantas instancias de cada tupla existen.'''
    ## El comando len(iterable) cuenta la cantidad de elementos que tiene el objeto iterable que le pasemos
    ## los elementos iterables pueden ser listas normales, Series de NumPy o Pandas, o diccionarios y otros tipos de datos.
    return len(elemento)
agrupacion_culinaria = restaurantes_dataframe_pares.pivot_table(index=["ciudades"], columns="culinaria", aggfunc=lambda x: funcion_agrupacion(x), fill_value=0)
agrupacion_culinaria
Out[4]:
culinaria Chapina China Italiana Thai Tica
ciudades
Guatemala 3 1 1 1 0
San José 1 1 1 0 2
San Salvador 0 1 1 0 1

¡Genial! Ahora ya tenemos agrupadas estas de una forma coherente. Ahora ya podemos seguir manipulando y editando estos datos. Pero, ¿qué tal si hacemos un poco más simple esta llamada? Al final nuestra función de agrupación lo unico que hace es contar la cantidad de tuplas sobre las cuales aplica el pivote. ¿Qué tal si lo hacemos un poco más simple?

In [5]:
agrupacion_culinaria = restaurantes_dataframe_pares.pivot_table(
    index=["ciudades"], 
    columns="culinaria", 
    aggfunc=len, ## Enviamos directamente la función de agrupación. Entre otras funcionas de agrupacíon útiles está np.sum (la función de suma de NumPy) y np.mean (media)
    fill_value=0)
agrupacion_culinaria
Out[5]:
culinaria Chapina China Italiana Thai Tica
ciudades
Guatemala 3 1 1 1 0
San José 1 1 1 0 2
San Salvador 0 1 1 0 1

Claro, la tabla resultante se comporta exactamente igual y tiene todas las propiedades nativas de los DataFrames. ¿Qué tal si limitamos la query a solo los lugares en ciudad de Guatemala?

In [6]:
agrupacion_culinaria.query('ciudades == ["Guatemala"]')
Out[6]:
culinaria Chapina China Italiana Thai Tica
ciudades
Guatemala 3 1 1 1 0
In [7]:
help(restaurantes_dataframe_pares.pivot_table)
Help on method pivot_table in module pandas.core.reshape.pivot:

pivot_table(values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All') method of pandas.core.frame.DataFrame instance
    Create a spreadsheet-style pivot table as a DataFrame. The levels in the
    pivot table will be stored in MultiIndex objects (hierarchical indexes) on
    the index and columns of the result DataFrame
    
    Parameters
    ----------
    data : DataFrame
    values : column to aggregate, optional
    index : column, Grouper, array, or list of the previous
        If an array is passed, it must be the same length as the data. The list
        can contain any of the other types (except list).
        Keys to group by on the pivot table index.  If an array is passed, it
        is being used as the same manner as column values.
    columns : column, Grouper, array, or list of the previous
        If an array is passed, it must be the same length as the data. The list
        can contain any of the other types (except list).
        Keys to group by on the pivot table column.  If an array is passed, it
        is being used as the same manner as column values.
    aggfunc : function or list of functions, default numpy.mean
        If list of functions passed, the resulting pivot table will have
        hierarchical columns whose top level are the function names (inferred
        from the function objects themselves)
    fill_value : scalar, default None
        Value to replace missing values with
    margins : boolean, default False
        Add all row / columns (e.g. for subtotal / grand totals)
    dropna : boolean, default True
        Do not include columns whose entries are all NaN
    margins_name : string, default 'All'
        Name of the row / column that will contain the totals
        when margins is True.
    
    Examples
    --------
    >>> df
       A   B   C      D
    0  foo one small  1
    1  foo one large  2
    2  foo one large  2
    3  foo two small  3
    4  foo two small  3
    5  bar one large  4
    6  bar one small  5
    7  bar two small  6
    8  bar two large  7
    
    >>> table = pivot_table(df, values='D', index=['A', 'B'],
    ...                     columns=['C'], aggfunc=np.sum)
    >>> table
              small  large
    foo  one  1      4
         two  6      NaN
    bar  one  5      4
         two  6      7
    
    Returns
    -------
    table : DataFrame
    
    See also
    --------
    DataFrame.pivot : pivot without aggregation that can handle
        non-numeric data

In [8]:
## Con el argumento Margins, Panda calcula los valores sumados de los totales por agrupación.
agrupacion_culinaria_m = restaurantes_dataframe_pares.pivot_table(
    index=["ciudades"],
    columns="culinaria",
    aggfunc=len,
    fill_value=0,
    margins=True,
    margins_name="Total")
agrupacion_culinaria_m
Out[8]:
culinaria Chapina China Italiana Thai Tica Total
ciudades
Guatemala 3.0 1.0 1.0 1.0 0.0 6.0
San José 1.0 1.0 1.0 0.0 2.0 5.0
San Salvador 0.0 1.0 1.0 0.0 1.0 3.0
Total 4.0 3.0 3.0 1.0 3.0 14.0

Múltiples Valores y Múltiples Indices

¿Qué tal si tenemos datos que tienen una estructura Jerárquica inherente? Podemos utilizar la misma forma de multi indexación que vimos en el seminario pasado, lo importante es que a la hora de la definición del índice, Pandas es capaz de manipularlos e inteligentemente ordenar los niveles acorde.

In [9]:
restaurantes_dataframe_pares['estrellas'] = [5,3,3,5,3,1,2,2,4,3,4,3,2,3]
restaurantes_dataframe_estrellas = restaurantes_dataframe_pares
restaurantes_dataframe_estrellas
Out[9]:
ciudades culinaria estrellas
0 Guatemala Chapina 5
1 Guatemala Chapina 3
2 Guatemala China 3
3 Guatemala Thai 5
4 Guatemala Italiana 3
5 Guatemala Chapina 1
6 San José Italiana 2
7 San José China 2
8 San José Tica 4
9 San José Chapina 3
10 San José Tica 4
11 San Salvador Tica 3
12 San Salvador Italiana 2
13 San Salvador China 3

Pivotando sobre la especialidad culinaria y estrellas, podemos las ciudades con la mayor oferta culinaria, o cuales tienen el mejor promedio de estrellas.

In [10]:
agrupacion_culinaria_promedio_estrellas = restaurantes_dataframe_estrellas.pivot_table(
    index=["ciudades"], 
    values=["culinaria", "estrellas"], 
    aggfunc={"culinaria":len,"estrellas":np.mean},
    fill_value=0)
agrupacion_culinaria_promedio_estrellas
Out[10]:
culinaria estrellas
ciudades
Guatemala 6 3.333333
San José 5 3.000000
San Salvador 3 2.666667

¿Qué tal si queremos ver cuantas estrellas en promedio tienen los restaurantes, por clase de comida, por ciudad?

In [11]:
agrupacion_culinaria_por_estrellas = restaurantes_dataframe_estrellas.pivot_table(
    index=["culinaria"], 
    values=["estrellas"], 
    columns=["estrellas"],
    aggfunc={"estrellas":np.mean},
    fill_value=0)
agrupacion_culinaria_por_estrellas
Out[11]:
estrellas
estrellas 1 2 3 4 5
culinaria
Chapina 1 0 3 0 5
China 0 2 3 0 0
Italiana 0 2 3 0 0
Thai 0 0 0 0 5
Tica 0 0 3 4 0
In [12]:
agrupacion_culinaria_por_estrellas = restaurantes_dataframe_estrellas.pivot_table(
    index=["culinaria"], 
    values=["estrellas"], 
    columns=["estrellas"],
    aggfunc={"estrellas":len},
    fill_value=0)
agrupacion_culinaria_por_estrellas
Out[12]:
estrellas
estrellas 1 2 3 4 5
culinaria
Chapina 1 0 2 0 1
China 0 1 2 0 0
Italiana 0 2 1 0 0
Thai 0 0 0 0 1
Tica 0 0 1 2 0

Hmm… esto no es muy útil, solo nos dice tautológicamente, que los restaurantes de ‘n’ estrellas tienen ‘n’ estrellas. ¿Pueden ver porque el error?

In [13]:
agrupacion_culinaria_por_estrellas = restaurantes_dataframe_estrellas.pivot_table(
    index=["ciudades"], 
    values=["estrellas"], 
    columns=["culinaria"], ## Aqui es obvio ver que lo que queremos es diferenciar por variedad culinaria.
    aggfunc={"estrellas":np.mean},
    fill_value=0)
agrupacion_culinaria_por_estrellas
Out[13]:
estrellas
culinaria Chapina China Italiana Thai Tica
ciudades
Guatemala 3 3 3 5 0
San José 3 2 2 0 4
San Salvador 0 3 2 0 3
In [14]:
agrupacion_culinaria_por_estrellas.plot(kind="bar")
<IPython.core.display.Javascript object>
Out[14]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fc53ffa1a58>

Entonces, recapitulando:

¿De qué nos sirven las tablas pivote?

¿Que clase de operación representan?

¿En que casos podemos usarlas?

Agrupando, parte dos

Ya vimos algunos de los criterios básicos de agrupación en el primer webinar, ahora podemos avanzar un poco, combinando agrupación con pivote.

Tambien podemos usar stack, que es otra forma de agrupación basada en índices.

In [15]:
maga_fitosanitario = pd.read_csv("MAGA - CERTIFICADOS FITOSANITARIOS.csv")
In [16]:
hashlib.md5("Hola".encode("UTF-8")).hexdigest()
Out[16]:
'f688ae26e9cfa3ba6235477831d5122e'
In [17]:
pd.set_option('display.float_format', lambda x: '%.1f' % x)

## Vamos a limpiar un poco de información
def ofusca_nombre(nombre):
    return humanhash.humanize(hashlib.md5(nombre.encode("UTF-8")).hexdigest())

maga_fitosanitario["Solicitante"] = maga_fitosanitario["Solicitante"].map(ofusca_nombre)
maga_fitosanitario["Fecha Autorización"] = maga_fitosanitario["Fecha Autorización"].map(pd.Timestamp)
In [18]:
def clean_q(input_object):
    from re import sub  ## importamos la función sub, que substituye utilizando patrones
    ## https://es.wikipedia.org/wiki/Expresión_regular
    
    ## NaN es un objeto especial que representa un valor numérico invalido, Not A Number.
    if input_object == NaN:
        return 0
    inp = unicode(input_object) # De objeto a un texto
    cleansed_00 = sub(r'\.000', '000', inp) 
    cleansed_nonchar = sub(r'[^0-9]+', '', cleansed_00)
    if cleansed_nonchar == '':
        return 0
    return cleansed_nonchar

maga_fitosanitario["Kg. Netos"] = maga_fitosanitario["Kg. Netos"].map(clean_q).astype(float)
In [36]:
maga_fitosanitario["Kg. Netos"].head()
Out[36]:
0   1360779.0
1    816467.0
2   3483624.0
3   3483624.0
4    151800.0
Name: Kg. Netos, dtype: float64
In [20]:
maga_fitosanitario = pd.read_csv("MAGA - CERTIFICADOS FITOSANITARIOS - LIMPIO.csv")
maga_fitosanitario.head()
Out[20]:
Incidente Fecha Autorización Solicitante Permiso Producto Categoría CIF $ Kg. Netos Aduana País procedencia País origen Otra fuente de origen
0 49 2014-04-04 sodium-pasta-glucose-mexico 142432 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 125.0 1360779.0 MELCHOR DE MENCOS Belice Belice NaN
1 50 2014-04-04 sodium-pasta-glucose-mexico 142425 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 75.0 816467.0 MELCHOR DE MENCOS Belice Belice NaN
2 275 2014-07-04 robert-vermont-one-robert 142479 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
3 276 2014-07-04 robert-vermont-one-robert 142480 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
4 177 2014-07-04 zebra-missouri-arkansas-island 142478 HARINA DE TRIGO HARINA DE TRIGO 81601.2 151800.0 TECUN UMAN México México NaN
In [21]:
maga_fitosanitario.groupby("Producto").sum().sort_values("CIF $", ascending=False).head(20)
Out[21]:
Permiso CIF $ Kg. Netos
Producto
MAIZ AMARILLO 53491946 183595249.4 2753711966.0
HARINA DE SOYA 18899910 56391529.9 177684115.0
ARROZ EN GRANZA 3201212 24568825.5 59041504.0
HARINA DE TRIGO 76664602 24272107.3 54953080.0
AJONJOLI NATURAL 9215686 15985707.0 20396870.0
ARROZ GRANZA 15088878 13883822.8 57978262.0
ALGODON 9014988 12028250.9 200973442.0
ALGODON SIN CARDAR NI PEINAR 5222374 8151960.6 19619672.0
MADERA DE PINO (SECA) 9285734 6498009.3 11404341.0
ARROZ 8758770 6111828.4 9988554.0
FRIJOL SOYA 1596785 5624212.9 17070365.0
MANZANAS 33723186 5591158.4 20625086.0
SEMOLA DE TRIGO 56157142 4567556.7 8012544.0
FRIJOL DE SOYA 434597 4262725.7 7231349.0
SEMILLA DE MELON 6774325 4132506.5 1113131.0
MAIZ BLANCO 4420695 4036005.2 161351106.0
AVENA PELADA Y ESTABILIZADA 3052102 3316810.3 51045868.0
MALTA DE CEBADA 440964 3160297.3 5316000.0
HARINA DE MAIZ 35816036 3134320.9 5236321.0
ALGODON SIN PEINAR NI CARDAR 1309843 2879479.1 1354471.0
In [22]:
maga_productos_pivot = maga_fitosanitario.pivot_table(
    index=["Categoría", "Producto"], 
    values=["CIF $", "Permiso","Kg. Netos"], 
    aggfunc={"CIF $":np.sum,"Permiso":len, "Kg. Netos": np.sum},
    fill_value=0)
In [23]:
maga_productos_pivot
Out[23]:
CIF $ Kg. Netos Permiso
Categoría Producto
AJONJOLI AJONJOLI DESCORTEZADO 250093.8 94375 1
AJONJOLI NATURAL 10702707.0 15867870 46
ALGODÓN ALGODON 12028250.9 200973442 62
ALGODON (BLANQUEADO) 52969.2 185857 1
ALGODON (EN PACAS) 35604.5 21805 1
ALGODON (PACAS) 48087.7 21830 1
ALGODON (SIN CARDAR NI PEINAR) 1934207.8 858309 10
ALGODON (SIN PEINAR NI CARDAR) 507479.4 238664 2
ALGODON BLANQUEADO 52658.4 175528 1
ALGODON SI CARDAR NI PEINAR 45158.1 19791 1
ALGODON SIN CARDAR NI PEINAR 8151960.6 19619672 36
ALGODON SIN PEINAR NI CARDAR 2879479.1 1354471 9
DESPERDICIO DE HILADOS DE ALGODON 32070.3 2148381 2
PACAS DE ALGODON 371093.7 196171 9
ALMIDON DE MAIZ ALMIDON (GLOBE AA SPV/25 KG) DE MAIZ 12500.0 20000 1
ALMIDON DE MAIZ 487747.5 872125 19
ALMIDON DE MAIZ (CORRUPAC) 13515.0 21250 1
ALMIDON DE MAIZ AA 7075.0 12500 1
ALMIDON DE MAIZ CORRUPAC 59038.5 105000 5
ALPISTE ALPISTE 54856.6 5048035 3
ARBOLES NATURALES SEMILLA DE TECA (TECTONA GRANDIS) 1388.6 60 1
SEMILLAS DE ARBOLES (Lluvia de oro y Papaya) 66.0 1 1
SEMILLAS DE ARBOLES (Lluvia de oro, Papaya y Strelizia) 127.6 22 1
ARROZ ARROZ 6111828.4 9988554 60
ARROZ (PARBOIL) 97606.0 11965890 2
ARROZ EN GRANO 20400.5 36114 4
ARROZ EN GRANZA 21791713.2 52447074 20
ARROZ EN ORO 55507.9 16873826 4
ARROZ ESCALDADO 240050.0 661234 10
ARROZ GRANZA 13883822.8 57978262 104
SUSTRATOS FIBRA DE COCO 78753.3 101682 4
FIBRA DE COCO (SUSTRATO) 117332.5 172140 7
FIBRA DE COCO TRATADA 132302.4 2770913 5
FIBRA DE ESTOPA DE COCO 375.0 6000 1
PEAT MOSS 655093.3 1226466 25
PEAT MOSS (BOLSAS DE ENRAIZADORES) 16425.0 48700 1
PEAT MOSS (SUSTRATO ) 3258.7 114288 1
PEAT MOSS (SUSTRATO DARK VEGETABLE MIX) 7151.8 23026 1
PEAT MOSS (SUSTRATO DE TURBA) 16068.0 71590 1
PEAT MOSS (SUSTRATO) 99434.2 263060 3
PEAT MOSS (TURBA) 213577.5 219207 3
PEAT MOSS SPHAGNUM (SUSTRATO DE TURBA) 15803.5 44000 1
PEAT SPHAGNUM 6905.0 21700 1
PEAT SPHAGNUM (SOD PEAT 0-20 NEUTRALIZED) 6870.5 22800 1
POLVO DE ESTOPA DE COCO 1750.0 8400 1
SUSTRATO ABONO DE TURBA 7795.6 22000 1
SUSTRATO DE COCO (COCOS NUCIFERA) 500.0 1004 1
SUSTRATO PEAT MOSS SPHAGNUM SPP (ABONO DE ORIGEN VEGETAL) 7900.2 25700 1
SUSTRATO SPAGNUM (MUSGO ESPANGINEO SECO) 12740.0 3185 1
TABACO EN RAMA SEMILLA DE TABACO 73396.5 10480 5
SEMILLAS DE TABACO 68060.4 35477 2
TELA DE YUTE SACO DE YUTE 42250.0 18200 1
SACO DE YUTE (40X28″ 460 grms/m2) 21624.0 15640 1
SACO DE YUTE (40×28″ 460 grms/m2) 43248.0 31280 2
SACOS DE YUTE 265198.1 669894 7
SACOS DE YUTE (28X40″ 750GR) 42250.0 18200 1
TELA DE YUTE 392247.7 307970 14
TRIGO EN ESTADO NATURAL SEMILLA DE TRIGO 300.0 20 2
TRIGO 201382.9 506000 24
TRIGO (ROJO SUAVE DE INVIERNO) 517598.6 1600000 2

1227 rows × 3 columns

In [24]:
maga_aduanas_pivot = maga_fitosanitario.pivot_table(
    index=["País origen", "Aduana"], 
    values=["CIF $", "Kg. Netos"],
    aggfunc={"CIF $":np.sum,"Kg. Netos":np.mean},
    fill_value=0)
maga_aduanas_pivot
Out[24]:
CIF $ Kg. Netos
País origen Aduana
ALEMANIA EXPRESS AEREO 102326.9 408.7
PUERTO QUETZAL 1727517.6 3000000.0
SANTO TOMAS DE CASTILLA 10050.2 16000.0
ARGENTINA PEDRO DE ALVARADO 3166.1 306817.0
PUERTO BARRIOS 163440.7 72900.0
PUERTO QUETZAL 187991.7 45965.1
SANTO TOMAS DE CASTILLA 410929.5 42113.6
AUSTRALIA EXPRESS AEREO 94350.0 2775.0
PUERTO QUETZAL 26932.2 21375.0
SANTO TOMAS DE CASTILLA 113750.0 3464.0
TECUN UMAN 5803.1 546201.0
Alemania EXPRESS AEREO 29503.2 48.5
Argentina SANTO TOMAS DE CASTILLA 15510.0 22000.0
BANGLADESH PUERTO QUETZAL 48274.4 16425.0
SANTO TOMAS DE CASTILLA 72000.0 537894.0
BELGICA EXPRESS AEREO 91348.9 1203.0
PUERTO QUETZAL 1855830.6 1500078.0
TECUN UMAN 192549.9 65179.2
BELICE MELCHOR DE MENCOS 547047.4 1097158.3
BOLIVIA PUERTO QUETZAL 91800.0 18000.0
BRASIL EXPRESS AEREO 121048.1 11588.5
PUERTO BARRIOS 245407.8 17108.0
SANTO TOMAS DE CASTILLA 3604767.2 382245.2
BURKINA FASO SANTO TOMAS DE CASTILLA 42888.0 19500.0
Belice MELCHOR DE MENCOS 45400.0 578402.5
CANADÁ EXPRESS AEREO 72.1 458.0
PUERTO BARRIOS 551903.1 51886.2
PUERTO QUETZAL 908538.0 175239.1
SANTO TOMAS DE CASTILLA 1231395.6 94833.4
CHAD PUERTO QUETZAL 35640.0 18000.0
PERÚ EXPRESS AEREO 2572758.1 12905.7
PUERTO QUETZAL 341275.7 14211.7
SANTO TOMAS DE CASTILLA 49007.5 5258.3
POLONIA EXPRESS AEREO 6366.9 30.0
PORTUGAL EXPRESS AEREO 667.3 12.0
Países Bajos EXPRESS AEREO 6890.2 40.0
SANTO TOMAS DE CASTILLA 586587.1 18211.0
Perú EXPRESS AEREO 2428.0 500.0
REINO UNIDO EXPRESS AEREO 225.2 42.0
REPÚBLICA DOMINICANA SANTO TOMAS DE CASTILLA 734869.1 1859816.9
SRI LANKA PUERTO QUETZAL 711008.5 52775.5
SANTO TOMAS DE CASTILLA 665303.2 381409.6
SUDÁFRICA EXPRESS AEREO 310826.5 271127.0
SUDÁN PUERTO QUETZAL 36826.8 12412.5
SUECIA EXPRESS AEREO 72927.0 392008.0
PUERTO QUETZAL 1827487.7 1500000.0
TAILANDIA EXPRESS AEREO 226567.5 16619.1
PUERTO QUETZAL 28765.0 1750.0
TAIWAN EXPRESS AEREO 205971.6 11966.5
VALLE NUEVO 1200.0 70.0
TANZANIA PUERTO QUETZAL 330340.0 20000.0
TURQUÍA EXPRESS AEREO 262.9 145.0
URUGUAY SANTO TOMAS DE CASTILLA 1485896.5 103641.5
UZBEKISTÁN SANTO TOMAS DE CASTILLA 106000.0 100240.0
Uruguay SANTO TOMAS DE CASTILLA 59007.8 108215.0
VENEZUELA PUERTO QUETZAL 13881240.0 254221.7
SANTO TOMAS DE CASTILLA 1185600.0 197600.0
VIETNAM EXPRESS AEREO 163930.0 10129.0
PUERTO QUETZAL 420550.0 19750.0
YEMEN PUERTO QUETZAL 167528.0 24300.0

186 rows × 2 columns

Que tal si indagamos mas en las categorias que se importan de cada país.

In [25]:
maga_aduanas_pivot = maga_fitosanitario.pivot_table(
    index=["País origen", "Aduana", "Categoría"], 
    values=["CIF $"], 
    aggfunc={"CIF $":np.sum},
    fill_value=0)
maga_aduanas_pivot
Out[25]:
CIF $
País origen Aduana Categoría
ALEMANIA EXPRESS AEREO ESQUEJES RIZOMAS BULBOS 72024.6
MATERIA PRIMA PARA ALIMENTOS 19900.5
SEMILLAS DE FLORES 475.8
SEMILLAS DE HORTALIZA 9926.0
PUERTO QUETZAL MALTA 1727517.6
SANTO TOMAS DE CASTILLA MALTA 10050.2
ARGENTINA PEDRO DE ALVARADO MAIZ PARA CONSUMO HUMANO 3166.1
PUERTO BARRIOS FRIJOL NEGRO 139899.7
FRIJOL PINTO 23541.0
PUERTO QUETZAL FRUTAS 60811.9
GRANOS 108570.0
SEMILLAS DE FLORES 18609.9
SANTO TOMAS DE CASTILLA GRANOS 171417.0
MAIZ PARA CONSUMO HUMANO 89333.0
MAIZ PARA ELAB DE CONCENTRADOS 34881.5
SEMILLAS DE FLORES 94778.0
SEMILLAS DE HORTALIZA 20520.0
AUSTRALIA EXPRESS AEREO SEMILLAS DE HORTALIZA 94350.0
PUERTO QUETZAL MADERA CEPILLADA 26932.2
SANTO TOMAS DE CASTILLA SEMILLAS DE HORTALIZA 113750.0
TECUN UMAN MADERA ASERRADA 5803.1
Alemania EXPRESS AEREO ESQUEJES RIZOMAS BULBOS 26028.2
SEMILLAS DE HORTALIZA 3475.0
Argentina SANTO TOMAS DE CASTILLA SEMILLAS DE FLORES 15510.0
BANGLADESH PUERTO QUETZAL TELA DE YUTE 48274.4
SANTO TOMAS DE CASTILLA TELA DE YUTE 72000.0
BELGICA EXPRESS AEREO SEMILLAS DE HORTALIZA 91348.9
PUERTO QUETZAL MALTA 1855830.6
TECUN UMAN ALMIDON DE MAIZ 10500.0
HARINA DE TRIGO 162327.3
SUDÁN PUERTO QUETZAL ESPECIAS 36826.8
SUECIA EXPRESS AEREO SEMILLAS DE HORTALIZA 72927.0
PUERTO QUETZAL MALTA 1827487.7
TAILANDIA EXPRESS AEREO ESQUEJES RIZOMAS BULBOS 10223.5
FLORES 4288.4
SEMILLAS DE FLORES 5.2
SEMILLAS DE FRUTAS 611.3
SEMILLAS DE HORTALIZA 210959.6
SEMOLA DE TRIGO 479.6
PUERTO QUETZAL SEMILLAS DE HORTALIZA 28765.0
TAIWAN EXPRESS AEREO ESQUEJES RIZOMAS BULBOS 1152.0
FLORES 27781.0
SEMILLAS DE FRUTAS 80970.4
SEMILLAS DE HORTALIZA 96068.2
VALLE NUEVO FLORES 1200.0
TANZANIA PUERTO QUETZAL SEMILLAS DE FLORES 330340.0
TURQUÍA EXPRESS AEREO SEMILLAS DE FLORES 223.7
SEMILLAS DE HORTALIZA 39.2
URUGUAY SANTO TOMAS DE CASTILLA ARROZ 463200.0
MADERA ASERRADA 902423.4
MADERA CEPILLADA 120273.1
UZBEKISTÁN SANTO TOMAS DE CASTILLA ARROZ 106000.0
Uruguay SANTO TOMAS DE CASTILLA MADERA CEPILLADA 59007.8
VENEZUELA PUERTO QUETZAL AJONJOLI 8910240.0
HORTALIZAS 4971000.0
SANTO TOMAS DE CASTILLA AJONJOLI 873600.0
HORTALIZAS 312000.0
VIETNAM EXPRESS AEREO SEMILLAS DE HORTALIZA 163930.0
PUERTO QUETZAL ESPECIAS 420550.0
YEMEN PUERTO QUETZAL ESPECIAS 167528.0

569 rows × 1 columns

In [26]:
maga_aduanas_pivot_top10 = maga_aduanas_pivot.sort_values("CIF $", ascending=False).head(10)
In [27]:
maga_aduanas_pivot_top10.plot(kind="barh")
<IPython.core.display.Javascript object>
Out[27]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fc53d5e0ac8>

Tambien es util mostrar la tabla, podemos ponerle un poco de estilo con la funcionalidad de Seaborn + Pandas

In [28]:
cm_paleta_verde = seaborn.light_palette("green", as_cmap=True)
s = maga_aduanas_pivot_top10.style.background_gradient(cmap=cm_paleta_verde)
s
Out[28]:
CIF $
País origen Aduana Categoría
ESTADOS UNIDOS PUERTO QUETZAL MAIZ PARA ELAB DE CONCENTRADOS 1.86755e+08
HARINA DE SOYA 5.61949e+07
ARROZ 3.27899e+07
SANTO TOMAS DE CASTILLA ALGODÓN 2.14909e+07
MEXICO TECUN UMAN HARINA DE TRIGO 1.86481e+07
VENEZUELA PUERTO QUETZAL AJONJOLI 8.91024e+06
ESTADOS UNIDOS PUERTO QUETZAL SOYA 8.52571e+06
FRUTAS 6.72475e+06
CHILE PUERTO QUETZAL MADERA ASERRADA 5.71528e+06
VENEZUELA PUERTO QUETZAL HORTALIZAS 4.971e+06
In [29]:
maga_aduanas_pivot = maga_fitosanitario.pivot_table(
    index=["País origen", "Aduana", "Categoría"], 
    values=["CIF $"], 
    aggfunc={"CIF $":np.sum},
    fill_value=0)
maga_aduanas_pivot
cm_paleta_verde = seaborn.light_palette("green", as_cmap=True)
s = maga_aduanas_pivot_top10.style.background_gradient(cmap=cm_paleta_verde)
s
Out[29]:
CIF $
País origen Aduana Categoría
ESTADOS UNIDOS PUERTO QUETZAL MAIZ PARA ELAB DE CONCENTRADOS 1.86755e+08
HARINA DE SOYA 5.61949e+07
ARROZ 3.27899e+07
SANTO TOMAS DE CASTILLA ALGODÓN 2.14909e+07
MEXICO TECUN UMAN HARINA DE TRIGO 1.86481e+07
VENEZUELA PUERTO QUETZAL AJONJOLI 8.91024e+06
ESTADOS UNIDOS PUERTO QUETZAL SOYA 8.52571e+06
FRUTAS 6.72475e+06
CHILE PUERTO QUETZAL MADERA ASERRADA 5.71528e+06
VENEZUELA PUERTO QUETZAL HORTALIZAS 4.971e+06
In [30]:
maga_fitosanitario
Out[30]:
Incidente Fecha Autorización Solicitante Permiso Producto Categoría CIF $ Kg. Netos Aduana País procedencia País origen Otra fuente de origen
0 49 2014-04-04 sodium-pasta-glucose-mexico 142432 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 125.0 1360779.0 MELCHOR DE MENCOS Belice Belice NaN
1 50 2014-04-04 sodium-pasta-glucose-mexico 142425 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 75.0 816467.0 MELCHOR DE MENCOS Belice Belice NaN
2 275 2014-07-04 robert-vermont-one-robert 142479 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
3 276 2014-07-04 robert-vermont-one-robert 142480 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
4 177 2014-07-04 zebra-missouri-arkansas-island 142478 HARINA DE TRIGO HARINA DE TRIGO 81601.2 151800.0 TECUN UMAN México México NaN
5 152 2014-07-04 beryllium-aspen-colorado-fish 142468 HARINA DE TRIGO HARINA DE TRIGO 11726.3 20866.0 SAN CRISTOBAL El Salvador El Salvador NaN
6 153 2014-07-04 beryllium-aspen-colorado-fish 142467 HARINA DE TRIGO HARINA DE TRIGO 11726.3 20866.0 SAN CRISTOBAL El Salvador El Salvador NaN
7 155 2014-07-04 beryllium-aspen-colorado-fish 142469 HARINA DE TRIGO HARINA DE TRIGO 11726.3 20866.0 SAN CRISTOBAL El Salvador El Salvador NaN
8 156 2014-07-04 beryllium-aspen-colorado-fish 142470 HARINA DE TRIGO HARINA DE TRIGO 11726.3 20866.0 SAN CRISTOBAL El Salvador El Salvador NaN
9 162 2014-07-04 robert-vermont-one-robert 142474 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
10 164 2014-07-04 robert-vermont-one-robert 142473 CASCARILLA DE ARROZ MATERIA PRIMA PARA CONCENTRADOS 2584.1 3483624.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
11 68 2014-07-04 kentucky-stream-crazy-winner 142440 CASCARILLA DE ARROZ MATERIA PRIMA PARA ALIMENTOS 500.0 16000.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
12 122 2014-07-04 echo-fillet-red-november 142463 MAIZ AMARILLO MAIZ PARA ELAB DE CONCENTRADOS 11250.0 68182.0 MELCHOR DE MENCOS Belice Belice NaN
13 123 2014-07-04 echo-fillet-red-november 142453 MAIZ AMARILLO MAIZ PARA ELAB DE CONCENTRADOS 11250.0 68182.0 MELCHOR DE MENCOS Belice Belice NaN
14 142 2014-07-04 montana-mockingbird-lactose-paris 142465 ARROZ PARBOIL ARROZ 49995.0 59875.0 SANTO TOMAS DE CASTILLA Estados Unidos Estados Unidos ORIGEN: ESTADO DE TEXAS.
15 467 2014-08-04 blue-alanine-aspen-ink 142545 MAIZ AMARILLO MAIZ PARA ELAB DE CONCENTRADOS 891909.3 3952402.0 PUERTO QUETZAL Estados Unidos Estados Unidos NaN
16 476 2014-08-04 august-alabama-william-black 142562 MAIZ AMARILLO MAIZ PARA ELAB DE CONCENTRADOS 156337.0 290316.0 SANTO TOMAS DE CASTILLA Estados Unidos Estados Unidos ORIGEN: ESTADO DE TEXAS.
17 530 2014-08-04 zebra-missouri-arkansas-island 142565 HARINA DE TRIGO HARINA DE TRIGO 81994.7 151800.0 TECUN UMAN MÓNACO MÓNACO NaN
18 352 2014-08-04 helium-jupiter-april-comet 142496 HARINA DE TRIGO HARINA DE TRIGO 10390.0 2268.0 TECUN UMAN México México NaN
19 353 2014-08-04 helium-jupiter-april-comet 142495 HARINA DE TRIGO HARINA DE TRIGO 10307.5 2268.0 TECUN UMAN México México NaN
20 354 2014-08-04 fifteen-venus-fruit-vermont 142494 HARINA DE TRIGO HARINA DE TRIGO 60564.0 13081.0 TECUN UMAN México México NaN
21 355 2014-08-04 king-one-saturn-nevada 142493 HARINA DE TRIGO HARINA DE TRIGO 61622.0 13081.0 TECUN UMAN México México NaN
22 295 2014-08-04 glucose-mike-magazine-table 142501 ARROZ GRANZA ARROZ 30055.3 71470.0 SAN CRISTOBAL EL SALVADOR ESTADOS UNIDOS ORIGEN: ESTADO DE LOUISIANA.
23 299 2014-08-04 cat-alabama-wisconsin-eleven 142500 ARROZ GRANZA ARROZ 454269.8 1093000.0 PUERTO QUETZAL ESTADOS UNIDOS ESTADOS UNIDOS NaN
24 342 2014-08-04 blossom-wyoming-lithium-stairway 142528 CASCARILLA DE ARROZ ARROZ 970.0 1363636.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
25 344 2014-08-04 blossom-wyoming-lithium-stairway 142526 CASCARILLA DE ARROZ ARROZ 970.0 1363636.0 PEDRO DE ALVARADO Nicaragua Nicaragua NaN
26 424 2014-08-04 helium-jupiter-april-comet 142523 HARINA DE TRIGO HARINA DE TRIGO 61094.2 13081.0 TECUN UMAN México México NaN
27 282 2014-08-04 massachusetts-stairway-fifteen-uniform 142498 ARROZ ARROZ 53000.0 100240.0 SANTO TOMAS DE CASTILLA UZBEKISTÁN UZBEKISTÁN NaN
28 448 2014-08-04 island-fish-chicken-purple 142540 HARINA DE TRIGO HARINA DE TRIGO 17990.0 31703.0 PEDRO DE ALVARADO El Salvador El Salvador NaN
29 450 2014-08-04 lion-paris-snake-floor 142550 HARINA DE TRIGO HARINA DE TRIGO 16992.5 31703.0 SAN CRISTOBAL El Salvador El Salvador NaN
7646 16472 2014-10-14 bravo-fish-king-carolina 148721 SEMILLA DE CHILE PIMIENTO Y TOMATE. SEMILLAS DE HORTALIZA 101.0 63.0 EXPRESS AEREO HOLANDA HOLANDA PAIS DE ORIGEN: CHINA Y HOLANDA.
7647 16484 2014-10-14 item-johnny-undress-william 148724 EJOTE FRANCES HORTALIZAS 4533.4 3878.0 SAN CRISTOBAL NICARAGUA NICARAGUA NaN
7648 16485 2014-10-14 cup-vermont-emma-johnny 148726 AJO HORTALIZAS 21332.3 26000.0 PUERTO QUETZAL CHINA CHINA NaN
7649 16486 2014-10-14 cup-vermont-emma-johnny 148725 AVENA EN HOJUELAS AVENA EN HOJUELAS 29357.6 52000.0 PUERTO QUETZAL CHILE CHILE NaN
7650 16487 2014-10-14 avocado-island-oxygen-two 148728 AGUACATE HASS FRUTAS 30438.0 23040.0 TECUN UMAN MEXICO MEXICO NaN
7651 16488 2014-10-14 friend-papa-delaware-bacon 148723 MANDARINA FRUTAS 2500.0 24000.0 LA MESILLA MEXICO MEXICO NaN
7652 16490 2014-10-14 island-earth-july-quebec 148729 GRAÑONES DE MAIZ (MAIZ AMARILLO SIN GERMEN) MAIZ PARA CONSUMO HUMANO 13850.8 19278.0 PUERTO BARRIOS ESTADOS UNIDOS ESTADOS UNIDOS ORIGEN: ESTADO DE ILLINOIS.
7653 16491 2014-10-14 island-earth-july-quebec 148730 GRAÑONES DE MAIZ (MAIZ AMARILLO SIN GERMEN) MAIZ PARA CONSUMO HUMANO 13850.8 19278.0 PUERTO BARRIOS ESTADOS UNIDOS ESTADOS UNIDOS ORIGEN: ESTADO DE ILLINOIS.
7654 16492 2014-10-14 ink-emma-fillet-maryland 148734 MANDARINA FRUTAS 1250.0 12000.0 LA MESILLA MEXICO MEXICO NaN
7655 16493 2014-10-14 ink-emma-fillet-maryland 148733 MANDARINA FRUTAS 2500.0 24000.0 LA MESILLA MEXICO MEXICO NaN
7656 16494 2014-10-14 six-low-bluebird-burger 148732 GLUTEN VITAL DE TRIGO MATERIA PRIMA PARA ALIMENTOS 2886.2 1000.0 TECUN UMAN MEXICO MEXICO NaN
7657 16495 2014-10-14 spaghetti-sad-queen-london 148737 MADERA ASERRADA DE PINO (TRATADA CON CCA) MADERA ASERRADA 19622.2 21602.0 AGUA CALIENTE HONDURAS HONDURAS NaN
7658 16496 2014-10-14 spaghetti-sad-queen-london 148731 MADERA ASERRADA DE PINO (TRATADA CON CCA) MADERA ASERRADA 15313.9 22405.0 AGUA CALIENTE HONDURAS HONDURAS NaN
7659 16500 2014-10-14 robert-berlin-march-pasta 148741 NARANJAS FRUTAS 12500.0 113635.0 ENTRE RIOS HONDURAS HONDURAS NaN
7660 16501 2014-10-14 robert-berlin-march-pasta 148740 NARANJAS FRUTAS 12500.0 113635.0 ENTRE RIOS HONDURAS HONDURAS NaN
7661 16502 2014-10-14 robert-berlin-march-pasta 148738 NARANJAS FRUTAS 15000.0 136362.0 ENTRE RIOS HONDURAS HONDURAS NaN
7662 16503 2014-10-14 robert-berlin-march-pasta 148739 NARANJAS FRUTAS 12500.0 113635.0 ENTRE RIOS HONDURAS HONDURAS NaN
7663 16504 2014-10-14 robert-berlin-march-pasta 148742 NARANJAS FRUTAS 12500.0 113635.0 ENTRE RIOS HONDURAS HONDURAS NaN
7664 16505 2014-10-14 robert-berlin-march-pasta 148743 NARANJAS FRUTAS 12500.0 113635.0 ENTRE RIOS HONDURAS HONDURAS NaN
7665 16506 2014-10-14 juliet-india-fourteen-music 148744 AGUACATE HASS FRUTAS 19000.0 20900.0 TECUN UMAN MEXICO MEXICO NaN
7666 16520 2014-10-14 lion-violet-lactose-robin 148735 SEMILLAS DE CEBOLLA SEMILLAS DE HORTALIZA 100.0 12.0 EXPRESS AEREO ESTADOS UNIDOS ESTADOS UNIDOS ORIGEN: ESTADO DE CALIFORNIA.
7667 16533 2014-10-14 leopard-september-mars-alabama 148745 MADERA DE PINO (SECA) MADERA ASERRADA 145393.9 241260.0 SANTO TOMAS DE CASTILLA BRASIL BRASIL NaN
7668 16534 2014-10-14 iowa-florida-cup-massachusetts 148747 UVAS FRUTAS 31138.0 13500.0 PUERTO QUETZAL ESTADOS UNIDOS ESTADOS UNIDOS ORIGEN: ESTADO DE CALIFORNIA.
7669 16537 2014-10-14 low-vermont-lactose-happy 148748 FRIJOL NEGRO (PARTIDO) FRIJOL NEGRO 50757.4 843696.0 PUERTO QUETZAL MEXICO MEXICO NaN
7670 16538 2014-10-14 alaska-high-steak-florida 148749 UVAS FRUTAS 29380.0 15200.0 PUERTO QUETZAL ESTADOS UNIDOS ESTADOS UNIDOS ORIGEN: ESTADO DE CALIFORNIA.
7671 16539 2014-10-14 alaska-high-steak-florida 148750 CAMOTE FRUTAS 1929.0 284091.0 AGUA CALIENTE HONDURAS HONDURAS NaN
7672 16540 2014-10-14 alaska-high-steak-florida 148751 GUAYABA FRUTAS 4115.4 170455.0 AGUA CALIENTE HONDURAS HONDURAS NaN
7673 16454 2014-10-14 colorado-aspen-romeo-oscar 148722 SEMILLA DE TOMATE SEMILLAS DE HORTALIZA 35.9 595.0 EXPRESS AEREO FRANCIA FRANCIA NaN
7674 11783 2014-10-14 missouri-harry-beer-social 148746 SEMILLA DE PEPINO (VARIEDAD SLICING) SEMILLAS DE HORTALIZA 105.0 399.0 EXPRESS AEREO ESTADOS UNIDOS MEXICO NaN
7675 14742 2014-10-14 charlie-violet-fish-ceiling 148736 SEMILLAS DE MELON, CALABAZA Y SANDIA SEMILLAS DE HORTALIZA 114179.4 681.0 EXPRESS AEREO ISRAEL ISRAEL PAIS DE ORIGEN: ISRAEL, CHILE Y CHINA.

7676 rows × 12 columns

In [31]:
maga_fitosanitario.groupby("Solicitante").sum().sort_values("CIF $", ascending=False).head(10)
Out[31]:
Permiso CIF $ Kg. Netos
Solicitante
papa-cola-cat-utah 2613794 51617483.5 2142316240.0
crazy-december-charlie-leopard 5407306 42385422.8 129173159.0
blue-alanine-aspen-ink 3914255 36726112.8 115987664.0
glucose-network-cardinal-december 1734642 19912544.7 47940184.0
butter-ceiling-uncle-salami 1448580 18986878.8 1276069585.0
nineteen-earth-stairway-nebraska 1738702 16256532.0 66034754.0
fanta-crazy-rugby-salami 8771752 15806525.0 19943562.0
september-red-hamper-ten 3044223 13971536.0 61956905.0
east-cup-summer-mango 2611047 12101661.5 39276980.0
oklahoma-sodium-nevada-four 12670668 9444222.0 100425831.0
In [32]:
maga_fitosanitario.pivot_table(
    index=["Solicitante", "País origen", "Categoría"], 
    values=["CIF $"], 
    aggfunc={"CIF $":np.sum},
    fill_value=0).sort_values("CIF $", ascending=False).head(10)
Out[32]:
CIF $
Solicitante País origen Categoría
papa-cola-cat-utah ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 34161962.8
crazy-december-charlie-leopard ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 28967653.8
blue-alanine-aspen-ink ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 20603138.9
papa-cola-cat-utah ESTADOS UNIDOS HARINA DE SOYA 17455520.7
glucose-network-cardinal-december ESTADOS UNIDOS ARROZ 17135432.4
nineteen-earth-stairway-nebraska ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 16256532.0
butter-ceiling-uncle-salami ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 14778445.5
crazy-december-charlie-leopard ESTADOS UNIDOS HARINA DE SOYA 12628533.6
september-red-hamper-ten ESTADOS UNIDOS MAIZ PARA ELAB DE CONCENTRADOS 10279335.3
fanta-crazy-rugby-salami VENEZUELA AJONJOLI 9783840.0
In [33]:
maga_fitosanitario.pivot_table(
    index=["País procedencia"],
    columns=["Aduana"],
    values=["CIF $"], 
    aggfunc={"CIF $":np.sum},
    fill_value=0).style.background_gradient(cmap=cm_paleta_verde)
Out[33]:
CIF $
Aduana AGUA CALIENTE EL CEIBO EL FLORIDO ENTRE RIOS EXPRESS AEREO FARDOS POSTALES LA ERMITA LA MESILLA MELCHOR DE MENCOS PEDRO DE ALVARADO PUERTO BARRIOS PUERTO QUETZAL SAN CRISTOBAL SANTO TOMAS DE CASTILLA TECUN UMAN VALLE NUEVO ZONA FRANCA DE GUATEMALA
País procedencia
ALEMANIA 0 0 0 0 102327 0 0 0 0 0 0 1.72752e+06 0 1.60688e+06 0 0 0
ARGENTINA 0 0 0 0 0 0 0 0 0 0 163441 187992 0 410929 0 0 0
AUSTRALIA 0 0 0 0 94350 0 0 0 0 0 0 26932.2 0 113750 0 0 0
Alemania 0 0 0 0 29503.2 0 0 0 0 0 0 0 0 0 0 0 0
Argentina 0 0 0 0 0 0 0 0 0 0 0 0 0 15510 0 0 0
BANGLADESH 0 0 0 0 0 0 0 0 0 0 0 48274.4 0 72000 0 0 0
BELGICA 0 0 0 0 0 0 0 0 0 0 0 1.85583e+06 0 0 192550 0 0
BELICE 0 0 0 0 0 0 0 0 547047 0 0 0 0 0 0 0 0
BOLIVIA 0 0 0 0 0 0 0 0 0 0 0 91800 0 0 0 0 0
BRASIL 0 0 0 0 121048 0 0 0 0 0 245408 0 0 3.58179e+06 0 0 0
BURKINA FASO 0 0 0 0 0 0 0 0 0 0 0 0 0 42888 0 0 0
Belice 0 0 0 0 0 0 0 0 45400 0 0 0 0 0 0 0 0
CANADÁ 0 0 0 0 72.11 0 0 0 0 0 551903 1.18703e+06 0 1.2314e+06 0 0 0
CHAD 0 0 0 0 0 0 0 0 0 0 0 77317.2 0 224059 0 0 0
CHILE 0 0 0 0 22150 0 0 0 0 5984.01 0 1.45996e+07 0 1.14601e+06 0 0 0
CHINA 0 0 0 0 35594.8 0 0 0 0 0 0 1.04992e+06 0 0 0 0 0
CHIPRE 0 0 0 0 3532.2 0 0 0 0 0 0 0 0 0 0 0 0
COLOMBIA 0 0 0 0 1.06184e+06 0 0 0 0 0 0 74263.4 0 233124 14780 0 0
COMORAS 0 0 0 0 2264.65 0 0 0 0 0 0 0 0 118725 0 0 0
COREA DEL SUR 0 0 0 0 231.2 0 0 0 0 0 0 0 0 0 0 0 0
COSTA RICA 0 0 0 0 2.51694e+06 0 0 0 0 595022 0 0 17022 0 0 0 0
Canadá 0 0 0 0 0 0 0 0 0 0 11320.3 0 0 22257.6 0 0 0
Chile 0 0 0 0 0 0 0 0 0 0 0 175952 0 0 0 0 0
China 0 0 0 0 0 0 0 0 0 0 0 49415 0 0 0 0 0
Colombia 0 0 0 0 10632.4 0 0 0 0 0 0 0 0 0 0 0 0
Costa Rica 0 0 0 0 304 0 0 0 0 0 0 0 0 0 0 0 0
ECUADOR 0 0 0 0 11121.1 0 0 0 0 0 0 0 0 0 0 0 0
EL SALVADOR 0 0 0 0 3380.89 0 0 0 0 3.15808e+06 0 0 1.75932e+07 0 0 19318.5 0
EMIRATOS ÁRABES UNIDOS 0 0 0 0 0 0 0 0 0 40834.8 15141.7 0 93246 0 0 0 0
ESPAÑA 0 0 0 0 31056.8 0 0 0 0 8929.65 0 0 0 71187.6 0 0 0
ESTADOS UNIDOS 0 0 0 0 6.74779e+06 781.92 0 0 0 452500 4.97125e+06 2.97986e+08 62815.5 3.63083e+07 0 0 0
ESTONIA 0 0 0 0 268577 0 0 0 0 0 0 2.37419e+06 0 618034 0 0 0
El Salvador 0 0 0 0 0 0 0 0 0 50653.3 0 0 159023 0 0 0 0
Estados Unidos 0 36.04 0 0 87632.5 0 0 0 0 0 177068 3.87267e+06 0 922944 0 0 0
Estonia 0 0 0 0 0 0 0 0 0 0 0 0 0 19145.3 0 0 0
FILIPINAS 0 0 0 0 1536 0 0 0 0 0 0 0 0 0 0 0 0
FRANCIA 0 0 0 0 121993 0 0 0 0 0 627655 0 0 1.29225e+06 0 0 0
GHANA 0 0 0 0 0 0 0 0 0 0 0 0 0 105007 0 0 0
GUATEMALA 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 95511
HOLANDA 0 0 0 0 6.99672e+06 0 0 0 0 5560 0 0 0 737879 3200 0 0
HONDURAS 1.04949e+06 0 1.11446e+06 1.89727e+06 18000 0 0 0 0 78172.1 0 0 0 0 0 0 0
HUNGRÍA 31815.6 0 0 45528.7 0 0 0 0 0 0 0 0 0 0 0 0 0
Honduras 70359.8 0 0 40300 0 0 0 0 0 0 0 0 0 0 0 0 0
INDIA 0 0 0 0 4650 0 0 0 0 0 0 789181 0 233004 0 0 0
ISRAEL 0 0 0 0 607326 0 0 0 0 0 0 0 0 0 0 0 0
ITALIA 0 0 0 0 24330.3 0 0 0 0 0 0 0 0 0 0 0 0
Israel 0 0 0 0 15891.7 0 0 0 0 0 0 0 0 0 0 0 0
JAPÓN 0 0 0 0 5499.54 0 0 0 0 0 0 43739.8 0 0 0 0 0
KENIA 0 0 0 0 10197.1 0 0 0 0 0 0 0 0 0 0 0 0
LAOS 0 0 0 0 0 0 0 0 0 0 8688.74 0 0 0 0 0 0
LATVIA 0 0 0 0 0 0 0 0 0 0 8693.31 0 0 54261.1 0 0 0
LETONIA 0 0 0 0 0 0 0 0 0 0 0 0 0 15052 0 0 0
LITUANIA 0 0 0 0 0 0 0 0 0 0 0 0 0 149491 0 0 0
MEXICO 0 0 0 0 33359.8 0 0 166788 0 0 0 675200 0 97502.1 2.49166e+07 0 0
MÓNACO 0 0 0 0 0 0 0 0 0 0 0 0 0 0 303410 0 0
México 0 0 0 0 0 0 0 1600 0 0 0 0 0 0 1.0659e+06 0 0
NAMIBIA 0 0 0 0 0 0 0 0 0 1940 0 0 0 0 0 0 0
NICARAGUA 0 0 0 0 1924.52 0 113631 0 0 4.06068e+06 0 0 547838 0 0 0 0
NIGERIA 0 0 0 0 0 0 0 0 0 130254 27383.8 0 19189.1 0 0 0 0
NUEVA ZELANDA 0 0 0 0 0 0 0 0 0 0 0 240022 0 47682 0 0 0
Nicaragua 0 0 0 0 0 0 12091 0 0 122190 0 0 28500.5 0 0 0 0
PANAMÁ 0 0 0 0 1957.53 0 0 0 0 0 0 0 20556 0 0 0 0
PERÚ 0 0 0 0 95392.9 0 0 0 0 0 0 341276 0 47076.6 0 0 0
POLONIA 0 0 0 0 6366.9 0 0 0 0 0 0 0 0 0 0 0 0
PORTUGAL 0 0 0 0 667.32 0 0 0 0 0 0 0 0 0 0 0 0
Países Bajos 0 0 0 0 6890.24 0 0 0 0 0 0 0 0 586587 0 0 0
Perú 0 0 0 0 2428 0 0 0 0 0 0 0 0 0 0 0 0
REINO UNIDO 0 0 0 0 3112.17 0 0 0 0 0 0 0 0 0 0 0 0
REPÚBLICA DOMINICANA 0 0 0 0 0 0 0 0 0 0 0 0 0 734869 0 0 0
SRI LANKA 0 0 0 0 0 0 0 0 0 0 0 711009 0 665303 0 0 0
SUDÁN 0 0 0 0 0 0 0 0 0 0 0 36826.8 0 0 0 0 0
SUECIA 0 0 0 0 0 0 0 0 0 0 0 1.82749e+06 0 0 0 0 0
TAILANDIA 0 0 0 0 133412 0 0 0 0 0 0 28765 0 0 0 0 0
TAIWAN 0 0 0 0 331696 0 0 0 0 0 0 0 0 0 0 0 0
TANZANIA 0 0 0 0 0 0 0 0 0 0 0 330340 0 0 0 0 0
URUGUAY 0 0 0 0 0 0 0 0 0 0 0 0 0 1.4859e+06 0 0 0
UZBEKISTÁN 0 0 0 0 0 0 0 0 0 0 0 0 0 106000 0 0 0
Uruguay 0 0 0 0 0 0 0 0 0 0 0 0 0 59007.8 0 0 0
VENEZUELA 0 0 0 0 0 0 0 0 0 0 0 1.38812e+07 0 1.1856e+06 0 0 0
VIETNAM 0 0 0 0 0 0 0 0 0 0 0 420550 0 0 0 0 0
YEMEN 0 0 0 0 0 0 0 0 0 0 0 167528 0 0 0 0 0

Que tal si queremos obtener el precio por kilogramo de cada producto y en base a eso obtener los productos mas ‘preciosos’.

In [35]:
maga_fitosanitario.to_csv("MAGA - CERTIFICADOS FITOSANITARIOS - LIMPIO.csv")