In [2]:
#importamos numpy y pandas
import numpy as np
import pandas as pd
#cargamos para manejar fechas
import datetime
from datetime import datetime, date

#configuramos el pandas para que nos muestre por pantalla como queremos
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 8)
pd.set_option('display.max_rows', 10)
pd.set_option('display.width', 60)

#usaremos matplotlib para los gráficos
import matplotlib.pyplot as plt
%matplotlib inline

#cargamos los datos y solamente leemos las columnas de la posicion 0 2 3 y 7

sp500 = pd.read_csv("tratamiento_datos/data/sp500.csv", index_col='Symbol', usecols=[0,2,3,7])

In [8]:
#creamos un dataframe aleatorio para practicar
np.random.seed(123456)
df=pd.DataFrame({'foo':np.random.random(1000000), 'key':range(100,1000100)})

In [10]:
#obtenemos un dato solamente
df[df.key==10099]


Out[10]:
           foo    key
9999  0.272283  10099

In [14]:
#Cuanto tiempo tardamos al hacer la selección por llave
%timeit df[df.key==10099]


1.32 ms ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [15]:
#pasamos las keys a que sean indices
df_with_index=df.set_index(['key'])
df_with_index[:5]


Out[15]:
          foo
key          
100  0.126970
101  0.966718
102  0.260476
103  0.897237
104  0.376750

In [16]:
df_with_index.loc[10099]


Out[16]:
foo    0.272283
Name: 10099, dtype: float64

In [17]:
#ahora con loc vemos a ver lo rapido que es
%timeit df_with_index.loc[10099]


89.7 µs ± 482 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [24]:
#indices básicos
temps = pd.DataFrame({'city':["Missoula", "Philadelphia"],"Temperature": [70, 80]})
print(temps)
print(temps.columns)


   Temperature          city
0           70      Missoula
1           80  Philadelphia
Index(['Temperature', 'city'], dtype='object')

In [28]:
#vamos a trabajar con indices
df_i64 = pd.DataFrame(np.arange(10,20), index=np.arange(0,10))
print(df_i64[:5])
print(df_i64.index)


    0
0  10
1  11
2  12
3  13
4  14
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

In [ ]: