In [1]:
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]:
In [5]:
df['W']
Out[5]:
In [6]:
# Pass a list of column names
df[['W', 'Z']]
Out[6]:
In [7]:
# SQL Syntax (NOT RECOMMENDED!)
df.W
Out[7]:
DataFrame Columns are just Series
In [8]:
type(df['W'])
Out[8]:
Creating a new column:
In [9]:
df['new'] = df['W'] + df['Y']
In [10]:
df
Out[10]:
Removing Columns
In [11]:
df.drop('new',
axis = 1)
Out[11]:
In [12]:
# Not inplace unless specified!
df
Out[12]:
In [13]:
df.drop('new',
axis = 1,
inplace = True)
In [14]:
df
Out[14]:
Can also drop rows this way:
In [15]:
df.drop('E',
axis = 0)
Out[15]:
Selecting Rows
In [16]:
df.loc['A']
Out[16]:
Or select based off of position instead of label
In [17]:
df.iloc[2]
Out[17]:
Selecting subset of rows and columns
In [18]:
df.loc['B', 'Y']
Out[18]:
In [19]:
df.loc[['A', 'B'],
['W', 'Y']]
Out[19]:
In [20]:
df
Out[20]:
In [21]:
df > 0
Out[21]:
In [22]:
df[df > 0]
Out[22]:
In [23]:
df[df['W'] > 0]
Out[23]:
In [24]:
df[df['W'] > 0]['Y']
Out[24]:
In [25]:
df[df['W'] > 0][['Y', 'X']]
Out[25]:
For two conditions you can use | and & with parenthesis:
In [26]:
df[(df['W'] > 0) & (df['Y'] > 1)]
Out[26]:
In [27]:
df
Out[27]:
In [28]:
# Reset to default 0,1...n index
df.reset_index()
Out[28]:
In [29]:
newind = 'CA NY WY OR CO'.split()
In [30]:
df['States'] = newind
In [31]:
df
Out[31]:
In [32]:
df.set_index('States')
Out[32]:
In [33]:
df
Out[33]:
In [34]:
df.set_index('States',
inplace = True)
In [35]:
df
Out[35]:
In [36]:
# Index Levels
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 [37]:
hier_index
Out[37]:
In [38]:
df = pd.DataFrame(np.random.randn(6, 2),
index=hier_index,columns = ['A', 'B'])
df
Out[38]:
Now let's show how to index this! For index hierarchy we use df.loc[], if this was on the columns axis, you would just use normal bracket notation df[]. Calling one level of the index returns the sub-dataframe:
In [39]:
df.loc['G1']
Out[39]:
In [40]:
df.loc['G1'].loc[1]
Out[40]:
In [41]:
df.index.names
Out[41]:
In [42]:
df.index.names = ['Group', 'Num']
In [43]:
df
Out[43]:
In [44]:
df.xs('G1')
Out[44]:
In [45]:
df.xs(['G1', 1])
Out[45]:
In [46]:
df.xs(1,
level = 'Num')
Out[46]: