import pandas as pd
sales = pd.DataFrame({'eggs': {0: 47, 1: 110, 2: 221, 3: 77, 4: 132, 5: 205},
'month': {0: 1, 1: 2, 2: 1, 3: 2, 4: 1, 5: 2},
'salt': {0: 12.0, 1: 50.0, 2: 89.0, 3: 87.0, 4: None, 5: 60.0},
'spam': {0: 17, 1: 31, 2: 72, 3: 20, 4: 52, 5: 55},
'state': {0: 'CA', 1: 'CA', 2: 'NY', 3: 'NY', 4: 'TX', 5: 'TX'}})
sales
sales.pivot('month','state','spam')
sales.pivot(index = 'month',
columns = 'state',
values = 'spam')
sales.pivot(index = 'month',
columns = 'state')
sales.pivot('state','month')
users = pd.DataFrame({'city': {0: 'Austin', 1: 'Dallas', 2: 'Austin', 3: 'Dallas'},
'signups': {0: 7, 1: 12, 2: 3, 3: 5},
'visitors': {0: 139, 1: 237, 2: 326, 3: 456},
'weekday': {0: 'Sun', 1: 'Sun', 2: 'Mon', 3: 'Mon'}})
users
users.pivot('weekday','city','visitors')
users.pivot(index='weekday', columns='city')
users
users2 = users.set_index(['city','weekday']).sort_index()
users2
users2.unstack(level = 'weekday')
users2.unstack()
users3 = users2.unstack(1)
users3
users3
users3.index
users3.stack()
users2
users2.unstack(level = 0)
users2.unstack(level = 'city')
users2.unstack(level = 'city').stack()
users.unstack()
pd.melt(users)
users2 = users.set_index(['city','weekday'])
users2
users2.unstack('weekday')
users2.unstack('city')
users2
users2.unstack(1)
users2.unstack(level = 0)
users2
users2.stack()
users2
users2.swaplevel()
users2.swaplevel(0,1)
users2.swaplevel().sort_index()
users
grouped = users.pivot('city','weekday','visitors')
grouped
grouped
test = grouped.copy()
test
test.index.name = 'cities'
test
test.reset_index()
grouped['city']=grouped.index
grouped
grouped
pd.melt(grouped)
pd.melt(grouped,'city')
pd.melt(grouped,'Sun')
pd.melt(grouped,id_vars='Mon')
pd.melt(grouped, id_vars=['city'],
var_name='whichdayofweek', value_name='visitors')
users
# Set the new index: users_idx
users_idx = users.set_index(['city', 'weekday'])
users_idx
pd.melt(users_idx, col_level=0)
users
pd.melt(users)
users
users.pivot_table(index='weekday', columns='city')
users.pivot('weekday','city')
users.pivot_table(index='weekday', columns='city',aggfunc='count')
users.pivot_table(index='weekday')
users.pivot_table(index='weekday',aggfunc='count')
users.pivot_table(index='weekday',aggfunc=len)
users
# Create the DataFrame with the appropriate pivot table: signups_and_visitors
users.pivot_table(index='weekday', aggfunc=sum)
# Add in the margins: signups_and_visitors_total
users.pivot_table(index='weekday', aggfunc=sum, margins=True)