DataFrames

DataFrames es el tipo de dato utilizado por Pandas, inspirado de la programacion en R, se puede considerar como un conjunto de Series agrupadas


In [1]:
# librerias
import pandas as pd
import numpy as np

In [2]:
from numpy.random import randn
np.random.seed(101)

In [3]:
df = pd.DataFrame(randn(5,4),index='A B C D E'.split(),columns='W X Y Z'.split())

In [4]:
df


Out[4]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

Indices y seleccion

Varios metodos para selecionar informacion de un DataFrame


In [187]:
df['W']


Out[187]:
A    2.706850
B    0.651118
C   -2.018168
D    0.188695
E    0.190794
Name: W, dtype: float64

In [5]:
# Pasar una lista de nombres de columnas
df[['W','Z']]


Out[5]:
W Z
A 2.706850 0.503826
B 0.651118 0.605965
C -2.018168 -0.589001
D 0.188695 0.955057
E 0.190794 0.683509

In [6]:
# Sintaxis tipo SQL (NO RECOMENDABLE!!!)
df.W


Out[6]:
A    2.706850
B    0.651118
C   -2.018168
D    0.188695
E    0.190794
Name: W, dtype: float64

Las columnas de los DataFrames son Series


In [7]:
type(df['W'])


Out[7]:
pandas.core.series.Series

Crear una nueva columna


In [8]:
df['new'] = df['W'] + df['Y']

In [9]:
df


Out[9]:
W X Y Z new
A 2.706850 0.628133 0.907969 0.503826 3.614819
B 0.651118 -0.319318 -0.848077 0.605965 -0.196959
C -2.018168 0.740122 0.528813 -0.589001 -1.489355
D 0.188695 -0.758872 -0.933237 0.955057 -0.744542
E 0.190794 1.978757 2.605967 0.683509 2.796762

Remover una columna


In [12]:
df.drop('new',axis=1)


Out[12]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

In [13]:
# Not inplace unless specified!
df


Out[13]:
W X Y Z new
A 2.706850 0.628133 0.907969 0.503826 3.614819
B 0.651118 -0.319318 -0.848077 0.605965 -0.196959
C -2.018168 0.740122 0.528813 -0.589001 -1.489355
D 0.188695 -0.758872 -0.933237 0.955057 -0.744542
E 0.190794 1.978757 2.605967 0.683509 2.796762

In [20]:
df.drop('new',axis=1,inplace=True)

In [21]:
df


Out[21]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

Se pueden borrar filas


In [22]:
df.drop('E',axis=0)


Out[22]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057

Seleccionar filas


In [23]:
df.loc['A']


Out[23]:
W    2.706850
X    0.628133
Y    0.907969
Z    0.503826
Name: A, dtype: float64

O seleccionar basado en la posicion en vez de la etiqueta


In [24]:
df.iloc[2]


Out[24]:
W   -2.018168
X    0.740122
Y    0.528813
Z   -0.589001
Name: C, dtype: float64

Seleccionar un grupo de filas y columnas


In [25]:
df.loc['B','Y']


Out[25]:
-0.84807698340363147

In [26]:
df.loc[['A','B'],['W','Y']]


Out[26]:
W Y
A 2.706850 0.907969
B 0.651118 -0.848077

Seleccion por condiciones

Una funcion importante de pandas es la seleccion por medio de condiciones muy similar a la de numpy utilizando corchetes


In [27]:
df


Out[27]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

In [28]:
df>0


Out[28]:
W X Y Z
A True True True True
B True False False True
C False True True False
D True False False True
E True True True True

In [29]:
df[df>0]


Out[29]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 NaN NaN 0.605965
C NaN 0.740122 0.528813 NaN
D 0.188695 NaN NaN 0.955057
E 0.190794 1.978757 2.605967 0.683509

In [30]:
df[df['W']>0]


Out[30]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

In [31]:
df[df['W']>0]['Y']


Out[31]:
A    0.907969
B   -0.848077
D   -0.933237
E    2.605967
Name: Y, dtype: float64

In [32]:
df[df['W']>0][['Y','X']]


Out[32]:
Y X
A 0.907969 0.628133
B -0.848077 -0.319318
D -0.933237 -0.758872
E 2.605967 1.978757

Para dos condiciones se pueden utilizar | y & con parentesis


In [33]:
df[(df['W']>0) & (df['Y'] > 1)]


Out[33]:
W X Y Z
E 0.190794 1.978757 2.605967 0.683509

Mas detalles de indices

Volver a generar los indices, o colocar otro valor


In [34]:
df


Out[34]:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509

In [35]:
# Valores por default 0,1...n index
df.reset_index()


Out[35]:
index W X Y Z
0 A 2.706850 0.628133 0.907969 0.503826
1 B 0.651118 -0.319318 -0.848077 0.605965
2 C -2.018168 0.740122 0.528813 -0.589001
3 D 0.188695 -0.758872 -0.933237 0.955057
4 E 0.190794 1.978757 2.605967 0.683509

In [36]:
newind = 'CA NY WY OR CO'.split()

In [37]:
df['States'] = newind

In [38]:
df


Out[38]:
W X Y Z States
A 2.706850 0.628133 0.907969 0.503826 CA
B 0.651118 -0.319318 -0.848077 0.605965 NY
C -2.018168 0.740122 0.528813 -0.589001 WY
D 0.188695 -0.758872 -0.933237 0.955057 OR
E 0.190794 1.978757 2.605967 0.683509 CO

In [39]:
df.set_index('States')


Out[39]:
W X Y Z
States
CA 2.706850 0.628133 0.907969 0.503826
NY 0.651118 -0.319318 -0.848077 0.605965
WY -2.018168 0.740122 0.528813 -0.589001
OR 0.188695 -0.758872 -0.933237 0.955057
CO 0.190794 1.978757 2.605967 0.683509

In [40]:
df


Out[40]:
W X Y Z States
A 2.706850 0.628133 0.907969 0.503826 CA
B 0.651118 -0.319318 -0.848077 0.605965 NY
C -2.018168 0.740122 0.528813 -0.589001 WY
D 0.188695 -0.758872 -0.933237 0.955057 OR
E 0.190794 1.978757 2.605967 0.683509 CO

In [41]:
df.set_index('States',inplace=True)

In [42]:
df


Out[42]:
W X Y Z
States
CA 2.706850 0.628133 0.907969 0.503826
NY 0.651118 -0.319318 -0.848077 0.605965
WY -2.018168 0.740122 0.528813 -0.589001
OR 0.188695 -0.758872 -0.933237 0.955057
CO 0.190794 1.978757 2.605967 0.683509

Multi indices y jerarquia de indices


In [43]:
# niveles de indices
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
hier_index = list(zip(outside,inside))
hier_index = pd.MultiIndex.from_tuples(hier_index)

In [44]:
hier_index


Out[44]:
MultiIndex(levels=[['G1', 'G2'], [1, 2, 3]],
           labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])

In [45]:
df = pd.DataFrame(np.random.randn(6,2),index=hier_index,columns=['A','B'])
df


Out[45]:
A B
G1 1 0.302665 1.693723
2 -1.706086 -1.159119
3 -0.134841 0.390528
G2 1 0.166905 0.184502
2 0.807706 0.072960
3 0.638787 0.329646

Para la jerarquia de indices utilizamos df.loc[], si esta en la columna se puede utilizar la sintaxis de corchetes df[] Hacer un llamado al nivel del indice nos generar un subDataFrame


In [46]:
df.loc['G1']


Out[46]:
A B
1 0.302665 1.693723
2 -1.706086 -1.159119
3 -0.134841 0.390528

In [47]:
df.loc['G1'].loc[1]


Out[47]:
A    0.302665
B    1.693723
Name: 1, dtype: float64

In [48]:
df.index.names


Out[48]:
FrozenList([None, None])

In [49]:
df.index.names = ['Group','Num']

In [50]:
df


Out[50]:
A B
Group Num
G1 1 0.302665 1.693723
2 -1.706086 -1.159119
3 -0.134841 0.390528
G2 1 0.166905 0.184502
2 0.807706 0.072960
3 0.638787 0.329646

In [51]:
df.xs('G1')


Out[51]:
A B
Num
1 0.302665 1.693723
2 -1.706086 -1.159119
3 -0.134841 0.390528

In [52]:
df.xs(['G1',1])


Out[52]:
A    0.302665
B    1.693723
Name: (G1, 1), dtype: float64

In [53]:
df.xs(1,level='Num')


Out[53]:
A B
Group
G1 0.302665 1.693723
G2 0.166905 0.184502