>>> stacked = df5.stack()# Pivot a level of column labels>>> stacked.unstack()# Pivot a level of index labels
1.4 Melt
# Gather columns into rows
pd.melt(df2,
id_vars=["Date"],
value_vars=["Type","Value"],
value_name="Observations")
2. Advanced Indexing
# Selecting>>> df3.loc[:,(df3>1).any()]# Select cols with any vals >1>>> df3.loc[:,(df3>1).all()]# Select cols with vals > 1>>> df3.loc[:,df3.isnull().any()]# Select cols with NaN>>> df3.loc[:,df3.notnull().all()]# Select cols without NaN# Indexing with Isin>>> df[(df.Country.isin(df2.Type))]# Find same elements>>> df3.filter(items=”a”,”b”])# Filter on values>>> df.select(lambda x:not x%5)# Select specific elements# Where>>> s.where(s >0)# Subset the data# Query>>> df6.query('second > first')# Query DataFrame
2.1 Setting/Resetting Index
# Set the index>>> df.set_index('Country')# Reset the index>>> df4 = df.reset_index()# Rename DataFrame>>> df = df.rename(index=str,
columns={"Country":"cntry","Capital":"cptl","Population":"ppltn"})
2.2 Reindexing
>>> s2 = s.reindex(['a','c','d','e','b'])# Forward Filling>>> df.reindex(range(4), method='ffill')
Country Capital Population
0 Belgium Brussels 111908461 India New Delhi 13031710352 Brazil Brasília 2078475283 Brazil Brasília 207847528# Backward Filling>>> s3 = s.reindex(range(5), method='bfill')0313233343
>>> df.dropna()# Drop NaN values>>> df3.fillna(df3.mean())# Fill NaN values with a predetermined value>>> df2.replace("a","f")# Replace values with others
4.5 Dates
>>> f2['Date']= pd.to_datetime(df2['Date'])>>> df2['Date']= pd.date_range('2000-1-1',
periods=6,
freq='M')>>> dates =[datetime(2012,5,1), datetime(2012,5,2)]>>> index = pd.DatetimeIndex(dates)>>> index = pd.date_range(datetime(2012,2,1), end, freq='BM')