En estas notas hago pruebas con la estructura de datos DataFrame.
In [1]:
#importacion estandar de pandas
import pandas as pd
import numpy as np
from IPython.display import display
data = [10,20,30]
df = pd.DataFrame(data)
df
Out[1]:
In [2]:
data = {'col1' : [1., 2., 3., 4.],
'col2' : [4., 3., 2., 1.]}
df = pd.DataFrame(data)
df
Out[2]:
In [3]:
data = {'col1' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'col2' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data)
df
Out[3]:
In [4]:
json_str = '[ {"a": 10, "d": 1, "c": 2, "b": 3}, \
{"a": 20, "d": 1, "c": 2, "b": 3}]'
df = pd.read_json(json_str)
df
Out[4]:
In [5]:
df = pd.read_json("data/dumb_data.json")
df
Out[5]:
In [6]:
df = pd.DataFrame(data, index=['d', 'b', 'a'], columns=['col2'])
df
Out[6]:
In [7]:
df = pd.read_csv("data/dumb_data.csv")
df
Out[7]:
In [8]:
from StringIO import StringIO
tsv = StringIO("""
Age Happiness # of pets Religion
10 Not happy 0 Not religious
20 Very happy 2 Islamic
2 Pretty happy 4 Hindu
""")
df = pd.read_csv(tsv, sep='\t')
df
Out[8]:
In [9]:
type(df["Age"])
Out[9]:
In [10]:
df.values
Out[10]:
In [11]:
df.index
Out[11]:
In [12]:
df.columns
Out[12]:
In [13]:
df["Age"]
Out[13]:
In [14]:
columnas = ["Age", "Happiness"]
df[columnas]
Out[14]:
In [15]:
df["Age"][0]
Out[15]:
In [16]:
filas = [0,18,19]
df["Age"][filas]
Out[16]:
In [17]:
df[(df['Age'] <= 30) & \
(df['Age'] >= 20)]
Out[17]:
In [18]:
df
Out[18]:
In [19]:
(df["# of pets"] / df["Age"]) + 100
Out[19]:
In [20]:
df_tmp = df.copy()
df_tmp["tmp"] = [1, 2, 3]
df_tmp
Out[20]:
In [21]:
df_tmp["tmp_factorial"] = df_tmp["tmp"].apply(np.math.factorial)
df_tmp
Out[21]:
In [22]:
json_map = {"Not happy" : 0, "Pretty happy" : 1, "Very happy" : 2}
df_tmp["tmp_Happiness"] = df_tmp["Happiness"].map(json_map)
df_tmp
Out[22]:
In [23]:
# axis es 0 para fila, 1 para columna
df_tmp.drop(labels="tmp_factorial", axis=1)
Out[23]:
In [24]:
df_tmp.drop(labels=["tmp_factorial", "tmp"], axis=1)
Out[24]:
In [25]:
# suponiendo que hay una fila con datos faltantes
df_tmp.loc[1, "Age"] = np.nan
df_tmp
Out[25]:
In [26]:
df_tmp = df_tmp.drop(labels=[1], axis=0)
df_tmp
Out[26]:
In [27]:
df_tmp.reset_index()
Out[27]:
In [28]:
df
Out[28]:
In [29]:
def f(row):
return row["# of pets"] * 1.0 / row["Age"]
print row
print
df["age/#pets"] = df.apply(f, axis=1) # recorriendo columnas
df
Out[29]:
In [30]:
df.describe(percentiles=[0.25, 0.5, 0.75])
Out[30]:
In [31]:
df.head()
Out[31]:
In [32]:
tsv = StringIO("""
Age Happiness # of pets Religion
10 Not happy 0 NaN
NaN Very happy 2 Islamic
2 Pretty happy 4 Hindu
""")
df = pd.read_csv(tsv, sep='\t')
df
Out[32]:
In [33]:
df.notnull()
Out[33]:
In [34]:
df.notnull().all()
Out[34]:
In [35]:
df.notnull().all().all()
Out[35]:
In [36]:
df.fillna(df.mean())
Out[36]:
In [37]:
df.dropna(subset=["Age"])
Out[37]:
In [38]:
df.dropna()
Out[38]: