<jupyter_start><jupyter_text>Assignment-1--- 1<jupyter_code>num_list = [21, 11, 19, 3,11,5]
# FInd sum of the numbers
num_sum = sum(num_list)
#divide the sum with length of the list
mean = num_sum / len(num_list)
print(num_list)
print("Mean of the above list of numbers is: ",mean)

num_list = [21, 11, 19, 3,11,5]
# FInd sum of the numbers
num_sum = sum(num_list)
#divide the sum with length of the list
mean = num_sum / len(num_list)
print(num_list)
print("Mean of the above list of numbers is: " + str(round(mean,2)))
import collections
# list of elements to calculate mode
num_list = [21, 13, 19, 13,19,13]
# Print the list
print(num_list)
# calculate the frequency of each item
data = collections.Counter(num_list)
data_list = dict(data)
# Print the items with frequency
print(data_list)
# Find the highest frequency
max_value = max(list(data.values()))
mode_val = [num for num, freq in data_list.items() if freq == max_value]
if len(mode_val) == len(num_list):
   print("No mode in the list")
else:
   print("The Mode of the list is : " + ', '.join(map(str, mode_val)))<jupyter_output>[21, 13, 19, 13, 19, 13]
{21: 1, 13: 3, 19: 2}
The Mode of the list is : 13<jupyter_text>2<jupyter_code>def variance(data):
     # Number of observations
     n = len(data)
     # Mean of the data
     mean = sum(data) / n
     # Square deviations
     deviations = [(x - mean) ** 2 for x in data]
     # Variance
     variance = sum(deviations) / n
     return variance
variance([4, 8, 6, 5, 3, 2, 8, 9, 2, 5])
import math
def variance(data):
     n = len(data)
     mean = sum(data) / n
     deviations = [(x - mean) ** 2 for x in data]
     variance = sum(deviations) / n
     return variance
def stdev(data):
     var = variance(data)
     std_dev = math.sqrt(var)
     return std_dev

stdev([4, 8, 6, 5, 3, 2, 8, 9, 2, 5])<jupyter_output><empty_output><jupyter_text>3<jupyter_code>#List 
L = [1, "a" , "string" , 1+2] 
print(L) 
L.append(6) 
print (L) 
L.pop() 
print(L) 
print(L[1])

#Tuple
tup = (1, "a", "string", 1+2) 
print(tup) 
print(tup[1]) 

#String
s = "Hello World"
for i in s : 
    print (i)

#Dictionary
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
print(dict1)<jupyter_output>[1, 'a', 'string', 3]
[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3]
a
(1, 'a', 'string', 3)
a
H
e
l
l
o
 
W
o
r
l
d
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}<jupyter_text>Assignment - 2<jupyter_code>import pandas as pd
from google.colab import files
uploaded=files.upload()
import io
df=pd.read_csv(io.BytesIO(uploaded["Pokemon.csv"]))
df.head()
df.tail()<jupyter_output><empty_output><jupyter_text>2 Practice 10 python programs using numpy libraries.<jupyter_code>import numpy as np
x = np.eye(5,dtype=int)
print("x =\n",x)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
import numpy as np
a = [[1, 2], [3, 4]]
x = np.array(a)
print("list to array:\n",x)
a2 = x.tolist()
print("array to list:\n",a2)
print(a == a2)
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
import numpy as np
x = np.random.random((5,5))
print("Original Array:")
print(x) 
xmin, xmax = x.min(), x.max()
print("Minimum and Maximum Values:")
print(xmin, xmax)
import numpy as np
nums =  np.random.rand(15)
print("Original array:")
print(nums)
print("\nSorted first 5 elements:")
print(nums[np.argpartition(nums,range(8))])
x = np.array([[1,2,3], [4,5,6]])
print("Original array: ")
print(x)
print("Cumulative sum of the elements along a given axis:")
r = np.cumsum(x)
print(r)
print("\nSum over rows for each of the 3 columns:")
r = np.cumsum(x,axis=0) 
print(r)
print("\nSum over columns for each of the 2 rows:")
r = np.cumsum(x,axis=1) 
print(r)
import numpy as np
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yestraday: ",yesterday)
today     = np.datetime64('today', 'D')
print("Today: ",today)
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow: ",tomorrow)
import numpy as np
x = np.array([' python exercises ', ' PHP  ', ' java  ', '  C++'], dtype=np.str)
print("Original Array:")
print(x)
stripped = np.char.strip(x)
print("\nRemove the leading and trailing whitespaces: ", stripped)<jupyter_output>Original Array:
[' python exercises ' ' PHP  ' ' java  ' '  C++']

Remove the leading and trailing whitespaces:  ['python exercises' 'PHP' 'java' 'C++']<jupyter_text>3 Practice 10 python methos using pandas libraries.<jupyter_code>#1.Write a Pandas program to add, subtract, multiple and divide two Pandas Series.
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds = ds1 - ds2
print(ds)
print("Multiply two Series:")
ds = ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds = ds1 / ds2
print(ds)
#2.Write a Pandas program to iterate over rows in a DataFrame.
import pandas as pd
import numpy as np
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9}, {'name':'Katherine','score':16.5}]
df = pd.DataFrame(exam_data)
for index, row in df.iterrows():
    print(row['name'], row['score'])
#3.Write a Pandas program to start index with different value rather than 0 in a given DataFrame.
import pandas as pd
df = pd.DataFrame({
    'school_code': ['s001','s002','s003','s001','s002','s004'],
    'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],
    'name': ['<NAME>','<NAME>','<NAME>', '<NAME>', '<NAME>', '<NAME>'],
    'date_of_birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
    'weight': [35, 37, 33, 30, 31, 32]})
     
print("Original DataFrame:")
print(df)
print("\nDefault Index Range:")
print(df.index)
df.index += 10 
print("\nNew Index Range:")
print(df.index)
print("\nDataFrame with new index:")
print(df)
#4.Write a Pandas program to extract only phone number from the specified column of a given DataFrame.
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
    'company_code': ['c0001','c0002','c0003', 'c0003', 'c0004'],
    'company_phone_no': ['Company1-Phone no. 4695168357','Company2-Phone no. 8088729013','Company3-Phone no. 6204658086', 'Company4-Phone no. 5159530096', 'Company5-Phone no. 9037952371']
    })
print("Original DataFrame:")
print(df)
def find_phone_number(text):
    ph_no = re.findall(r"\b\d{10}\b",text)
    return "".join(ph_no)
df['number']=df['company_phone_no'].apply(lambda x: find_phone_number(x))
print("\Extracting numbers from dataframe columns:")
print(df)
#5.Write a Pandas program to Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame.
import pandas as pd
df1 = pd.DataFrame({'A': [None, 0, None], 'B': [3, 4, 5]})
df2 = pd.DataFrame({'A': [1, 1, 3], 'B': [3, None, 3]})
df1.combine_first(df2)
print("Original DataFrames:")
print(df1)
print("--------------------")
print(df2)
print("\nMerge two dataframes with different columns:")
result = df1.combine_first(df2)
print(result)
#6.Write a Pandas program to create
#a) Datetime object for Jan 15 2012.
#b) Specific date and time of 9:20 pm.
#c) Local date and time.
#d) A date without time.
#e) Current date.
#f) Time from a datetime.
#g) Current local time.
import datetime
from datetime import datetime
print("Datetime object for Jan 11 2012:")
print(datetime(2012, 1, 11))
print("\nSpecific date and time of 9:20 pm") 
print(datetime(2011, 1, 11, 21, 20))
print("\nLocal date and time:")
print(datetime.now())
print("\nA date without time: ")
print(datetime.date(datetime(2012, 5, 22)))
print("\nCurrent date:")
print(datetime.now().date())
print("\nTime from a datetime:")
print(datetime.time(datetime(2012, 12, 15, 18, 12)))
print("\nCurrent local time:") 
print(datetime.now().time())
#7.Write a Pandas program to find out the alcohol consumption details in the year '1986' or '1989' where WHO region is 'Americas' or 'Europe' from the world alcohol consumption dataset.
import pandas as pd
url = "https://raw.githubusercontent.com/Akash2oc98/18cse037-gietu_DMDW_lab-work/main/world_alcohol.csv"
w_a_con =pd.read_csv(url)
print("World alcohol consumption sample data:")
print(w_a_con.head())
print("\nThe world alcohol consumption details in the year ‘1986’ or ‘1989’ where  WHO region is ‘Americas’  or 'Europe':")
print(w_a_con[((w_a_con['Year']==1985) | (w_a_con['Year']==1989)) & ((w_a_con['WHO region']=='Americas') | (w_a_con['WHO region']=='Europe'))].head(10))
#8
"""Write a Pandas program to split the following dataset using group by on 'salesman_id' and find the first order date for each group.

Test Data:

    ord_no  purch_amt    ord_date  customer_id  salesman_id
0    70001     150.50  2012-10-05         3002         5002
1    70009     270.65  2012-09-10         3001         5003
2    70002      65.26  2012-10-05         3001         5001
3    70004     110.50  2012-08-17         3003         5003
4    70007     948.50  2012-09-10         3002         5002
5    70005    2400.60  2012-07-27         3002         5001
6    70008    5760.00  2012-09-10         3001         5001
7    70010    1983.43  2012-10-10         3004         5003
8    70003    2480.40  2012-10-10         3003         5003
9    70012     250.45  2012-06-27         3002         5002
10   70011      75.29  2012-08-17         3003         5003
11   70013    3045.60  2012-04-25         3001         5001"""
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,70009,70002,70004,70007,70005,70008,70010,70003,70012,70011,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': ['2012-10-05','2012-09-10','2012-10-05','2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002],
'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5004,5003,5002,5004,5001]})
print("Original Orders DataFrame:")
print(df)
print("\nGroupby to find first order date for each group(salesman_id):")
result = df.groupby('salesman_id')['ord_date'].min()
print(result)
#9
"""Write a Pandas program to find and replace the missing values in a given DataFrame which do not have any valuable information.

Example:
Missing values: ?, --
Replace those values with NaN

Test Data:

   ord_no purch_amt    ord_date customer_id salesman_id
0   70001     150.5           ?        3002        5002
1     NaN    270.65  2012-09-10        3001        5003
2   70002     65.26         NaN        3001           ?
3   70004     110.5  2012-08-17        3003        5001
4     NaN     948.5  2012-09-10        3002         NaN
5   70005    2400.6  2012-07-27        3001        5002
6      --      5760  2012-09-10        3001        5001
7   70010         ?  2012-10-10        3004           ?
8   70003     12.43  2012-10-10          --        5003
9   70012    2480.4  2012-06-27        3002        5002
10    NaN    250.45  2012-08-17        3001        5003
11  70013    3045.6  2012-04-25        3001          --   """
import numpy as np
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,np.nan,70002,70004,np.nan,70005,"--",70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,"?",12.43,2480.4,250.45, 3045.6],
'ord_date': ['?','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,"--",3002,3001,3001],
'salesman_id':[5002,5003,"?",5001,np.nan,5002,5001,"?",5003,5002,5003,"--"]})
print("Original Orders DataFrame:")
print(df)
print("\nReplace the missing values with NaN:")
result = df.replace({"?": np.nan, "--": np.nan})
print(result)
#10.Create a dataframe of ten rows, four columns with random values. Write a Pandas program to display bar charts in dataframe on specified columns.
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
print("\nBar charts in dataframe:")
df.style.bar(subset=['B', 'C'], color='#d65f5f')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1689616967394745, 'fraction_numerical': 0.13105413105413105, 'mean_word_length': 3.7758881330309904, 'pattern_counts': {'":': 2, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '206402', 'license': 'Apache-2.0', 'n_tokens_mistral': 5832, 'n_tokens_neox': 4779, 'n_words': 1327, 'path': 'Assignment_1&2.ipynb', 'repo_name': 'amritesh-21/amritesh18cse076', 'size': '12673'}