Transformando datos
Filtrado
import pandas as pd
# Condicion simple
df[df['edad'] > 25]
# Condiciones multiples
df[(df['edad'] > 25) & (df['ciudad'] == 'Madrid')]
df[(df['edad'] < 20) | (df['edad'] > 30)]
# isin: multiples valores
df[df['ciudad'].isin(['Madrid', 'Barcelona'])]
# query: sintaxis SQL-like
df.query('edad > 25 and ciudad == "Madrid"')
Ordenamiento
# Por una columna
df.sort_values('edad')
df.sort_values('edad', ascending=False)
# Por multiples columnas
df.sort_values(['ciudad', 'edad'], ascending=[True, False])
# Por indice
df.sort_index()
Agregar y modificar columnas
# Nueva columna
df['edad_en_meses'] = df['edad'] * 12
# Con funcion
df['categoria'] = df['edad'].apply(lambda x: 'joven' if x < 30 else 'adulto')
# Con condiciones
df['nivel'] = np.where(df['puntos'] > 100, 'alto', 'bajo')
# Multiples condiciones
condiciones = [
df['edad'] < 18,
df['edad'] < 30,
df['edad'] >= 30
]
valores = ['menor', 'joven', 'adulto']
df['grupo'] = np.select(condiciones, valores)
GroupBy: Agregaciones
# Agrupar y agregar
df.groupby('ciudad')['edad'].mean()
df.groupby('ciudad')['edad'].agg(['mean', 'min', 'max', 'count'])
# Multiples columnas
df.groupby(['ciudad', 'genero'])['salario'].mean()
# Multiples agregaciones
df.groupby('ciudad').agg({
'edad': 'mean',
'salario': ['min', 'max', 'sum'],
'nombre': 'count'
})
Pivot Tables
# Tabla pivot (como Excel)
pd.pivot_table(
df,
values='ventas',
index='producto',
columns='mes',
aggfunc='sum'
)
# Cross tabulation
pd.crosstab(df['genero'], df['ciudad'])