Using inplace parameter in pandas
This introduction to pandas is derived from Data School's pandas Q&A with my own notes and code.
Using "inplace" parameter in pandas¶
In [1]:
import pandas as pd
In [2]:
url = 'http://bit.ly/uforeports'
ufo = pd.read_csv(url)
In [3]:
ufo.shape
Out[3]:
In [4]:
ufo.head()
Out[4]:
In [5]:
# dropping City column
ufo.drop('City', axis=1).head()
Out[5]:
In [7]:
# you can see that the City column is not gone
# drop() method has inplace=False as default
ufo.head()
Out[7]:
In [8]:
# you want to change to inplace=True to affect the underlying data
ufo.drop('City', axis=1, inplace=True)
In [9]:
ufo.head()
Out[9]:
In [11]:
# dropna with how='any' would drop any row with 'NaN'
ufo.dropna(how='any').shape
Out[11]:
In [14]:
ufo.shape
# as you can see, we lose a lot of rows because of dropna
# but the underlying data has not been affected because inplace=False for .dropna()
Out[14]:
In [15]:
# some examples with inplace=False
# most are set to False
# ufo.set_index()
# ufo.rename()
In [16]:
# you can not use inplace=True and use an assignment instead
ufo = ufo.set_index('Time')
In [17]:
ufo.tail()
Out[17]:
In [18]:
ufo.fillna(method='bfill').tail()
Out[18]:
In [19]:
ufo.fillna(method='ffill').tail()
Out[19]: