fillna() sort_values() groupby()

Perform following operations using Pandas

  1. Filling NaN with String
  2. Sorting based on column values
  3. groupby()

Filling NaN with String

Program

import numpy as np
import pandas as pd

#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,np.nan,10.6], 'onroadprice':[np.nan,29.6,14.8]})
print("Cars Information with NaN:")
print(cars)
#Replacing NaN with empty string
cars.fillna('',inplace=True)
print("Cars Information after replacing NaN with empty string:")
print(cars)

Output

Cars Information with NaN:
   name  showroomprice  onroadprice
0  benz           12.5          NaN
1   bmw            NaN         29.6
2  tata           10.6         14.8
Cars Information after replacing NaN with empty string:
   name showroomprice onroadprice
0  benz          12.5
1   bmw                      29.6
2  tata          10.6        14.8

Sorting based on column values

Program

import pandas as pd

#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,24.6,10.6], 'onroadprice':[16.8,29.6,14.8]})
print("Cars Information:")
print(cars)
#Sorting column values
cars.sort_values(by='showroomprice',inplace=True)
print("After sorting cars by show room price, Cars Information:")
print(cars)

Output

Cars Information:
   name  showroomprice  onroadprice
0  benz           12.5         16.8
1   bmw           24.6         29.6
2  tata           10.6         14.8
After sorting cars by show room price, Cars Information:
   name  showroomprice  onroadprice
2  tata           10.6         14.8
0  benz           12.5         16.8
1   bmw           24.6         29.6

groupby()

Program

import pandas as pd

#Creating DataFrame
cars = pd.DataFrame({'name':['tata','benz','bmw','tata'], 'showroomprice':[6.32,12.5,24.6,10.6], 'onroadprice':[8.02,16.8,29.6,14.8]})
print("Cars Information:")
print(cars)
#Cars Information Grouping by name
grouped = cars.groupby(by="name").sum()
print("After grouping cars companies by name, Cars Information:")
print(grouped)

Output

Cars Information:
   name  showroomprice  onroadprice
0  tata           6.32         8.02
1  benz          12.50        16.80
2   bmw          24.60        29.60
3  tata          10.60        14.80
After grouping cars companies by name, Cars Information:
      showroomprice  onroadprice
name
benz          12.50        16.80
bmw           24.60        29.60
tata          16.92        22.82