Friday, June 28, 2019

python Pivot, Pivot_table and Sorting a dataframe

Pivot, Pivot_table and dataframe sorting

import numpy as np
import pandas as pd
 
'''
d1 = {'item':['AC','TV','CAR','TV','BIKE','TV'],
      'quantity':[28,36,25,14,25,48],
      'rate':[11,22,33,44,55,66],
      'country':['USA','PAK','JAPAN','USA','INDIA','JAPAN']}
df = pd.DataFrame(d1)
print(df)
#p=df.pivot(index='country', columns='item', values='rate')
p=df.pivot(index='country', columns='item')
print('*'*20)
print(p)
'''

************************************************************

'''
d1 = {'item':['AC','TV','CAR','TV','BIKE','TV'],
      'quantity':[28,36,25,14,25,48],
      'rate':[11,22,33,44,55,66],
      'country':['USA','PAK','JAPAN','USA','INDIA','USA']}
df = pd.DataFrame(d1)
print(df)
#p=df.pivot_table(index='country', columns='item',values='rate')
#p=df.pivot_table(index='country', columns='item',values='rate', aggfunc='mean')
p=df.pivot_table(index='country', columns='item',values='rate', aggfunc='count')
print('*'*20)
print(p)
'''

************************************************************
 
'''
d1 = {'item':['AC','TV','CAR','TV','BIKE','TV'],
      'quantity':[28,36,25,14,25,48],
      'rate':[11,22,33,44,55,66],
      'country':['USA','PAK','JAPAN','USA','INDIA','USA']}
df = pd.DataFrame(d1)
print(df)
#p=df.pivot_table(index=['country','item'],values=['rate','quantity'])
p=df.pivot_table(index=['country','item'],values=['rate'],aggfunc='count')
print('*'*20)
print(p)
'''

 ************************************************************
 
'''
d1 = {'item':['AC','TV','CAR','TV','BIKE','TV'],
      'quantity':[28,36,25,14,25,48],
      'rate':[11,22,33,44,55,66],
      'country':['USA','PAK','JAPAN','USA','INDIA','USA']}
df = pd.DataFrame(d1)
print(df)
print('*'*30)
#print(df.sort_values(['country']))
#print(df.sort_values(['country'], ascending=False))
#print(df.sort_values(['country','item']))
#print(df.sort_values(['country','item'],ascending=False))
#print(df.sort_values(['country','item'], ascending=[False,False]))
print('*'*30)
print(df.sort_values(['country'],inplace=True))
print(df)
'''

************************************************************
 
'''
d1 = {'item':['AC','TV','CAR','TV','BIKE','TV'],
      'quantity':[28,36,25,14,25,48],
      'rate':[11,22,33,44,55,66],
      'country':['USA','PAK','JAPAN','USA','INDIA','USA']}
df = pd.DataFrame(d1)
print(df)
print('*'*30)
print(df.sort_index(ascending=False))
'''

No comments:

Post a Comment