Subject – Data Analytics with Python
Problem 11:
Data Set Sales Data
Problem Write a Pandas program to replace NaNs with median
or mean of the specified columns in a given
DataFrame.
import pandas as pd
import numpy as np
# Sample data
data = {
'ord_no': [70001, [Link], 70002, 70004, [Link], 70005, [Link],
70010, 70003, 70012, [Link], 70013],
'purch_amt': [150.5, [Link], 65.26, 110.5, 948.5, [Link], 5760,
1983.43, [Link], 250.45, 75.29, 3045.6],
'sale_amt': [10.5, 20.65, [Link], 11.5, 98.5, [Link], 57, 19.43,
[Link], 25.45, 75.29, 35.6],
'ord_date': ['5/10/2012', '10/9/2012', [Link], '17-08-2012',
'10/9/2012', '27-07-2012', '10/9/2012', '10/10/2012', '10/10/2012', '27-
06-2012', '17-08-2012', '25-04-2012'],
'customer_id': [3002, 3001, 3001, 3003, 3002, 3001, 3001, 3004,
3003, 3002, 3001, 3001],
'salesman_id': [5002, 5003, 5001, [Link], 5002, 5001, 5001,
[Link], 5003, 5002, 5003, [Link]]
}
# Create a DataFrame
df = [Link](data)
# Replace NaN values in 'purch_amt' and 'sale_amt' columns with
their median
df['purch_amt'] = df['purch_amt'].fillna(df['purch_amt'].median())
df['sale_amt'] = df['sale_amt'].fillna(df['sale_amt'].median())
print(df)