code
stringlengths
63
8.54k
code_length
int64
11
747
# How to get column names in Pandas dataframe in Python # Import pandas package  import pandas as pd       # making data frame  data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")       # calling head() method   # storing in new variable  data_top = data.head()       # display  data_top 
41
# Write a Python program to convert true to 1 and false to 0. x = 'true' x = int(x == 'true') print(x) x = 'abcd' x = int(x == 'true') print(x)
32
# Write a Pandas program to rename names of columns and specific labels of the Main Index of the MultiIndex dataframe. import pandas as pd import numpy as np sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'], ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']] sales_tuples = list(zip(*sales_arrays)) sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city']) print(sales_tuples) print("\nConstruct a Dataframe using the said MultiIndex levels: ") df = pd.DataFrame(np.random.randn(8, 5), index=sales_index) print(df) print("\nRename the columns name of the said dataframe") df1 = df.rename(columns={0: "col1", 1: "col2", 2:"col3", 3:"col4", 4:"col5"}) print(df1) print("\nRename specific labels of the main index of the DataFrame") df2 = df1.rename(index={"sale2": "S2", "city2": "C2"}) print(df2)
106
# How to check horoscope using Python import requests from bs4 import BeautifulSoup
13
# Write a Python program to create a new Arrow object, cloned from the current one. import arrow a = arrow.utcnow() print("Current datetime:") print(a) cloned = a.clone() print("\nCloned datetime:") print(cloned)
30
# Write a Python program to count occurrences of a substring in a string. str1 = 'The quick brown fox jumps over the lazy dog.' print() print(str1.count("fox")) print()
28
# Write a Python program to find the maximum and minimum product from the pairs of tuple within a given list. def tuple_max_val(nums): result_max = max([abs(x * y) for x, y in nums] ) result_min = min([abs(x * y) for x, y in nums] ) return result_max,result_min nums = [(2, 7), (2, 6), (1, 8), (4, 9)] print("The original list, tuple : ") print(nums) print("\nMaximum and minimum product from the pairs of the said tuple of list:") print(tuple_max_val(nums))
78
# Drop rows from the dataframe based on certain condition applied on a column in Python # importing pandas as pd import pandas as pd    # Read the csv file and construct the  # dataframe df = pd.read_csv('nba.csv')    # Visualize the dataframe print(df.head(15)    # Print the shape of the dataframe print(df.shape)
51
# Write a NumPy program to create random vector of size 15 and replace the maximum value by -1. import numpy as np x = np.random.random(15) print("Original array:") print(x) x[x.argmax()] = -1 print("Maximum value replaced by -1:") print(x)
38
# Quote Guessing Game using Web Scraping in Python import requests from bs4 import BeautifulSoup from csv import writer from time import sleep from random import choice    # list to store scraped data all_quotes = []    # this part of the url is constant base_url = "http://quotes.toscrape.com/"    # this part of the url will keep changing url = "/page/1"    while url:          # concatenating both urls     # making request     res = requests.get(f"{base_url}{url}")     print(f"Now Scraping{base_url}{url}")     soup = BeautifulSoup(res.text, "html.parser")        # extracting all elements     quotes = soup.find_all(class_="quote")        for quote in quotes:         all_quotes.append({             "text": quote.find(class_="text").get_text(),             "author": quote.find(class_="author").get_text(),             "bio-link": quote.find("a")["href"]         })     next_btn = soup.find(_class="next")     url = next_btn.find("a")["href"] if next_btn else None     sleep(2)    quote = choice(all_quotes) remaining_guesses = 4 print("Here's a quote:  ") print(quote["text"])    guess = '' while guess.lower() != quote["author"].lower() and remaining_guesses > 0:     guess = input(         f"Who said this quote? Guesses remaining {remaining_guesses}")            if guess == quote["author"]:         print("CONGRATULATIONS!!! YOU GOT IT RIGHT")         break     remaining_guesses -= 1            if remaining_guesses == 3:         res = requests.get(f"{base_url}{quote['bio-link']}")         soup = BeautifulSoup(res.text, "html.parser")         birth_date = soup.find(class_="author-born-date").get_text()         birth_place = soup.find(class_="author-born-location").get_text()         print(             f"Here's a hint: The author was born on {birth_date}{birth_place}")            elif remaining_guesses == 2:         print(             f"Here's a hint: The author's first name starts with: {quote['author'][0]}")            elif remaining_guesses == 1:         last_initial = quote["author"].split(" ")[1][0]         print(             f"Here's a hint: The author's last name starts with: {last_initial}")            else:         print(             f"Sorry, you ran out of guesses. The answer was {quote['author']}")
225
# Write a Python program to check if a given function returns True for at least one element in the list. def test(lst, fn = lambda x: x): return all(not fn(x) for x in lst) print(test([1, 0, 2, 3], lambda x: x >= 3 )) print(test([1, 0, 2, 3], lambda x: x < 0 )) print(test([2, 2, 4, 4]))
59
# Program to Find subtraction of two matrices # Get size of matrix row_size=int(input("Enter the row Size Of the Matrix:")) col_size=int(input("Enter the columns Size Of the Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) matrix1=[] # Taking input of the 2nd matrix print("Enter the Matrix Element:") for i in range(row_size): matrix1.append([int(j) for j in input().split()]) # Compute Subtraction of two matrices sub_matrix=[[0 for i in range(col_size)] for i in range(row_size)] for i in range(len(matrix)): for j in range(len(matrix[0])): sub_matrix[i][j]=matrix[i][j]-matrix1[i][j] # display the Subtraction of two matrices print("Subtraction of the two Matrices is:") for m in sub_matrix: print(m)
111
# Write a Python program to sort unsorted numbers using Pigeonhole sorting. #Ref. https://bit.ly/3olnZcd def pigeonhole_sort(a): # size of range of values in the list (ie, number of pigeonholes we need) min_val = min(a) # min() finds the minimum value max_val = max(a) # max() finds the maximum value size = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size holes = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(x, int), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 nums = [4, 3, 5, 1, 2] print("\nOriginal list:") print(nums) pigeonhole_sort(nums) print("Sorted order is:", nums) nums = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] print("\nOriginal list:") print(nums) pigeonhole_sort(nums) print("Sorted order is:", nums)
172
# Write a Python program to test whether a passed letter is a vowel or not. def is_vowel(char): all_vowels = 'aeiou' return char in all_vowels print(is_vowel('c')) print(is_vowel('e'))
27
# Write a Python program to create a flat list of all the values in a flat dictionary. def test(flat_dict): return list(flat_dict.values()) students = { 'Theodore': 19, 'Roxanne': 20, 'Mathew': 21, 'Betty': 20 } print("\nOriginal dictionary elements:") print(students) print("\nCreate a flat list of all the values of the said flat dictionary:") print(test(students))
52
# Write a NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10. import numpy as np x = np.random.randint(0, 11, 5) print("Vector of length 5 filled with arbitrary integers from 0 to 10:") print(x)
42
# Python Program to Count the Number of Vowels Present in a String using Sets s=raw_input("Enter string:") count = 0 vowels = set("aeiou") for letter in s: if letter in vowels: count += 1 print("Count of the vowels is:") print(count)
40
# Calculate the mean across dimension in a 2D NumPy array in Python # Importing Library import numpy as np    # creating 2d array arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])    # Calculating mean across Rows row_mean = np.mean(arr, axis=1)    row1_mean = row_mean[0] print("Mean of Row 1 is", row1_mean)    row2_mean = row_mean[1] print("Mean of Row 2 is", row2_mean)    row3_mean = row_mean[2] print("Mean of Row 3 is", row3_mean)       # Calculating mean across Columns column_mean = np.mean(arr, axis=0)    column1_mean = column_mean[0] print("Mean of column 1 is", column1_mean)    column2_mean = column_mean[1] print("Mean of column 2 is", column2_mean)    column3_mean = column_mean[2] print("Mean of column 3 is", column3_mean)
107
# Write a Python program to Find all duplicate characters in string from collections import Counter    def find_dup_char(input):        # now create dictionary using counter method     # which will have strings as key and their      # frequencies as value     WC = Counter(input)     j = -1                   # Finding no. of  occurrence of a character     # and get the index of it.     for i in WC.values():         j = j + 1         if( i > 1 ):             print WC.keys()[j],    # Driver program if __name__ == "__main__":     input = 'geeksforgeeks'     find_dup_char(input)
86
# How to add timestamp to CSV file in Python # Importing required modules import csv from datetime import datetime       # Here we are storing our data in a # variable. We'll add this data in # our csv file rows = [['GeeksforGeeks1', 'GeeksforGeeks2'],         ['GeeksforGeeks3', 'GeeksforGeeks4'],         ['GeeksforGeeks5', 'GeeksforGeeks6']]    # Opening the CSV file in read and # write mode using the open() module with open(r'YOUR_CSV_FILE.csv', 'r+', newline='') as file:        # creating the csv writer     file_write = csv.writer(file)        # storing current date and time     current_date_time = datetime.now()        # Iterating over all the data in the rows      # variable     for val in rows:                    # Inserting the date and time at 0th          # index         val.insert(0, current_date_time)                    # writing the data in csv file         file_write.writerow(val)
121
# Write a Pandas program to create a graphical analysis of UFO (unidentified flying object) sighted by month. import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r'ufo.csv') df['Date_time'] = df['Date_time'].astype('datetime64[ns]') df["ufo_yr"] = df.Date_time.dt.month months_data = df.ufo_yr.value_counts() months_index = months_data.index # x ticks months_values = months_data.get_values() plt.figure(figsize=(15,8)) plt.xticks(rotation = 60) plt.title('UFO sighted by Month') plt.xlabel("Months") plt.ylabel("Number of sighting") months_plot = sns.barplot(x=months_index[:60],y=months_values[:60], palette = "Oranges")
69
# Write a NumPy program to replace all the nan (missing values) of a given array with the mean of another array. import numpy as np array_nums1 = np.arange(20).reshape(4,5) array_nums2 = np.array([[1,2,np.nan],[4,5,6],[np.nan, 7, np.nan]]) print("Original arrays:") print(array_nums1) print(array_nums2) print("\nAll the nan of array_nums2 replaced by the mean of array_nums1:") array_nums2[np.isnan(array_nums2)]= np.nanmean(array_nums1) print(array_nums2)
52
# Program to count the number of digits in an integer. ''' Write a Python program to count the number of digits in an integer. or    Write a program to count the number of digits in an integer using Python ''' n=int(input("Enter a number:")) count=0 while n>0:    n=int(n/10)    count+=1 print("The number of digits in the number is", count)
58
# Find the sum of odd numbers using recursion def SumOdd(num1,num2):    if num1>num2:        return 0    return num1+SumOdd(num1+2,num2)num1=1print("Enter your Limit:")num2=int(input())print("Sum of all odd numbers in the given range is:",SumOdd(num1,num2))
28
# Write a Pandas program to create a time series combining hour and minute. import pandas as pd result = pd.timedelta_range(0, periods=30, freq="1H20T") print("For a frequency of 1 hours 20 minutes, here we have combined the hour (H) and minute (T):\n") print(result)
42
# Write a Python program to calculate the average of a given list, after mapping each element to a value using the provided function. def average_by(lst, fn = lambda x: x): return sum(map(fn, lst), 0.0) / len(lst) print(average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n'])) print(average_by([{ 'n': 10 }, { 'n': 20 }, { 'n': -30 }, { 'n': 60 }], lambda x: x['n']))
75
# Convert covariance matrix to correlation matrix using Python import numpy as np import pandas as pd # loading in the iris dataset for demo purposes dataset = pd.read_csv("iris.csv") dataset.head()
30
# Write a NumPy program to compute the 80th percentile for all elements in a given array along the second axis. import numpy as np x = np.arange(12).reshape((2, 6)) print("\nOriginal array:") print(x) r1 = np.percentile(x, 80, 1) print("\n80th percentile for all elements of the said array along the second axis:") print(r1)
51
# Convert Lowercase to Uppercase using the inbuilt function str=input("Enter the String(Lower case):") print("Upper case String is:", str.upper())
18
# Write a Pandas program to replace missing white spaces in a given string with the least frequent character. import pandas as pd str1 = 'abc def abcdef icd' print("Original series:") print(str1) ser = pd.Series(list(str1)) element_freq = ser.value_counts() print(element_freq) current_freq = element_freq.dropna().index[-1] result = "".join(ser.replace(' ', current_freq)) print(result)
48
# Python Program to Implement Johnson’s Algorithm class Graph: def __init__(self): # dictionary containing keys that map to the corresponding vertex object self.vertices = {}   def add_vertex(self, key): """Add a vertex with the given key to the graph.""" vertex = Vertex(key) self.vertices[key] = vertex   def get_vertex(self, key): """Return vertex object with the corresponding key.""" return self.vertices[key]   def __contains__(self, key): return key in self.vertices   def add_edge(self, src_key, dest_key, weight=1): """Add edge from src_key to dest_key with given weight.""" self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)   def does_edge_exist(self, src_key, dest_key): """Return True if there is an edge from src_key to dest_key.""" return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])   def __len__(self): return len(self.vertices)   def __iter__(self): return iter(self.vertices.values())     class Vertex: def __init__(self, key): self.key = key self.points_to = {}   def get_key(self): """Return key corresponding to this vertex object.""" return self.key   def add_neighbour(self, dest, weight): """Make this vertex point to dest with given edge weight.""" self.points_to[dest] = weight   def get_neighbours(self): """Return all vertices pointed to by this vertex.""" return self.points_to.keys()   def get_weight(self, dest): """Get weight of edge from this vertex to dest.""" return self.points_to[dest]   def set_weight(self, dest, weight): """Set weight of edge from this vertex to dest.""" self.points_to[dest] = weight   def does_it_point_to(self, dest): """Return True if this vertex points to dest.""" return dest in self.points_to     def johnson(g): """Return distance where distance[u][v] is the min distance from u to v.   distance[u][v] is the shortest distance from vertex u to v.   g is a Graph object which can have negative edge weights. """ # add new vertex q g.add_vertex('q') # let q point to all other vertices in g with zero-weight edges for v in g: g.add_edge('q', v.get_key(), 0)   # compute shortest distance from vertex q to all other vertices bell_dist = bellman_ford(g, g.get_vertex('q'))   # set weight(u, v) = weight(u, v) + bell_dist(u) - bell_dist(v) for each # edge (u, v) for v in g: for n in v.get_neighbours(): w = v.get_weight(n) v.set_weight(n, w + bell_dist[v] - bell_dist[n])   # remove vertex q # This implementation of the graph stores edge (u, v) in Vertex object u # Since no other vertex points back to q, we do not need to worry about # removing edges pointing to q from other vertices. del g.vertices['q']   # distance[u][v] will hold smallest distance from vertex u to v distance = {} # run dijkstra's algorithm on each source vertex for v in g: distance[v] = dijkstra(g, v)   # correct distances for v in g: for w in g: distance[v][w] += bell_dist[w] - bell_dist[v]   # correct weights in original graph for v in g: for n in v.get_neighbours(): w = v.get_weight(n) v.set_weight(n, w + bell_dist[n] - bell_dist[v])   return distance     def bellman_ford(g, source): """Return distance where distance[v] is min distance from source to v.   This will return a dictionary distance.   g is a Graph object which can have negative edge weights. source is a Vertex object in g. """ distance = dict.fromkeys(g, float('inf')) distance[source] = 0   for _ in range(len(g) - 1): for v in g: for n in v.get_neighbours(): distance[n] = min(distance[n], distance[v] + v.get_weight(n))   return distance     def dijkstra(g, source): """Return distance where distance[v] is min distance from source to v.   This will return a dictionary distance.   g is a Graph object. source is a Vertex object in g. """ unvisited = set(g) distance = dict.fromkeys(g, float('inf')) distance[source] = 0   while unvisited != set(): # find vertex with minimum distance closest = min(unvisited, key=lambda v: distance[v])   # mark as visited unvisited.remove(closest)   # update distances for neighbour in closest.get_neighbours(): if neighbour in unvisited: new_distance = distance[closest] + closest.get_weight(neighbour) if distance[neighbour] > new_distance: distance[neighbour] = new_distance   return distance     g = Graph() print('Menu') print('add vertex <key>') print('add edge <src> <dest> <weight>') print('johnson') print('display') print('quit')   while True: do = input('What would you like to do? ').split()   operation = do[0] if operation == 'add': suboperation = do[1] if suboperation == 'vertex': key = int(do[2]) if key not in g: g.add_vertex(key) else: print('Vertex already exists.') elif suboperation == 'edge': src = int(do[2]) dest = int(do[3]) weight = int(do[4]) if src not in g: print('Vertex {} does not exist.'.format(src)) elif dest not in g: print('Vertex {} does not exist.'.format(dest)) else: if not g.does_edge_exist(src, dest): g.add_edge(src, dest, weight) else: print('Edge already exists.')   elif operation == 'johnson': distance = johnson(g) print('Shortest distances:') for start in g: for end in g: print('{} to {}'.format(start.get_key(), end.get_key()), end=' ') print('distance {}'.format(distance[start][end]))   elif operation == 'display': print('Vertices: ', end='') for v in g: print(v.get_key(), end=' ') print()   print('Edges: ') for v in g: for dest in v.get_neighbours(): w = v.get_weight(dest) print('(src={}, dest={}, weight={}) '.format(v.get_key(), dest.get_key(), w)) print()   elif operation == 'quit': break
747
# Program to print mirrored right triangle star pattern print("Enter the row size:") row_size=int(input()) for out in range(row_size+1):     for j in range(row_size-out):         print(" ",end="")     for p in range(out+1):         print("*",end="")     print("\r")
30
# Write a Python program to extract Strings between HTML Tags # importing re module import re    # initializing string test_str = '<b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.'    # printing original string print("The original string is : " + str(test_str))    # initializing tag tag = "b"    # regex to extract required strings reg_str = "<" + tag + ">(.*?)</" + tag + ">" res = re.findall(reg_str, test_str)    # printing result print("The Strings extracted : " + str(res))
80
# Write a Pandas program to split the following dataframe into groups, group by month and year based on order date and find the total purchase amount year wise, month wise. 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': ['05-10-2012','09-10-2012','05-10-2013','08-17-2013','10-09-2013','07-27-2014','10-09-2012','10-10-2012','10-10-2012','06-17-2014','07-08-2012','04-25-2012'], 'customer_id':[3001,3001,3005,3001,3005,3001,3005,3001,3005,3001,3005,3005], 'salesman_id': [5002,5005,5001,5003,5002,5001,5001,5006,5003,5002,5007,5001]}) print("Original Orders DataFrame:") print(df) df['ord_date']= pd.to_datetime(df['ord_date']) print("\nYear wise Month wise purchase amount:") result = df.groupby([df['ord_date'].dt.year, df['ord_date'].dt.month]).agg({'purch_amt':sum}) print(result)
67
# Write a Python program to create a new list taking specific elements from a tuple and convert a string value to integer. student_data = [('Alberto Franco','15/05/2002','35kg'), ('Gino Mcneill','17/05/2002','37kg'), ('Ryan Parkes','16/02/1999', '39kg'), ('Eesha Hinton','25/09/1998', '35kg')] print("Original data:") print(student_data) students_data_name = list(map(lambda x:x[0], student_data)) students_data_dob = list(map(lambda x:x[1], student_data)) students_data_weight = list(map(lambda x:int(x[2][:-2]), student_data)) print("\nStudent name:") print(students_data_name) print("Student name:") print(students_data_dob) print("Student weight:") print(students_data_weight)
62
# Write a NumPy program to compute the sum of the diagonal element of a given array. import numpy as np m = np.arange(6).reshape(2,3) print("Original matrix:") print(m) result = np.trace(m) print("Condition number of the said matrix:") print(result)
37
# Write a Python program to convert a given list of tuples to a list of strings using map function. def tuples_to_list_string(lst): result = list(map(' '.join, lst)) return result colors = [('red', 'pink'), ('white', 'black'), ('orange', 'green')] print("Original list of tuples:") print(colors) print("\nConvert the said list of tuples to a list of strings:") print(tuples_to_list_string(colors)) names = [('Sheridan','Gentry'), ('Laila','Mckee'), ('Ahsan','Rivas'), ('Conna','Gonzalez')] print("\nOriginal list of tuples:") print(names) print("\nConvert the said list of tuples to a list of strings:") print(tuples_to_list_string(names))
77
# Write a Python program to check if two given lists contain the same elements regardless of order. def check_same_contents(nums1, nums2): for x in set(nums1 + nums2): if nums1.count(x) != nums2.count(x): return False return True nums1 = [1, 2, 4] nums2 = [2, 4, 1] print("Original list elements:") print(nums1) print(nums2) print("\nCheck two said lists contain the same elements regardless of order!") print(check_same_contents(nums1, nums2)) nums1 = [1, 2, 3] nums2 = [1, 2, 3] print("\nOriginal list elements:") print(nums1) print(nums2) print("\nCheck two said lists contain the same elements regardless of order!") print(check_same_contents(nums1, nums2)) nums1 = [1, 2, 3] nums2 = [1, 2, 4] print("\nOriginal list elements:") print(nums1) print(nums2) print("\nCheck two said lists contain the same elements regardless of order!") print(check_same_contents(nums1, nums2))
119
# Write a NumPy program to check element-wise True/False of a given array where signbit is set. import numpy as np x = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) print("Original array: ") print(x) r1 = np.signbit(x) r2 = x < 0 assert np.array_equiv(r1, r2) print(r1)
48
# Write a Python Program for Bitonic Sort # Python program for Bitonic Sort. Note that this program # works only when size of input is a power of 2. # The parameter dir indicates the sorting direction, ASCENDING # or DESCENDING; if (a[i] > a[j]) agrees with the direction, # then a[i] and a[j] are interchanged.*/ def compAndSwap(a, i, j, dire):     if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] > a[j]):         a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order, # if dir = 1, and in descending order otherwise (means dir=0). # The sequence to be sorted starts at index position low, # the parameter cnt is the number of elements to be sorted. def bitonicMerge(a, low, cnt, dire):     if cnt > 1:         k = cnt/2         for i in range(low , low+k):             compAndSwap(a, i, i+k, dire)         bitonicMerge(a, low, k, dire)         bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively # sorting its two halves in opposite sorting orders, and then # calls bitonicMerge to make them in the same order def bitonicSort(a, low, cnt,dire):     if cnt > 1:           k = cnt/2           bitonicSort(a, low, k, 1)           bitonicSort(a, low+k, k, 0)           bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N # in ASCENDING order def sort(a,N, up):     bitonicSort(a,0, N, up) # Driver code to test above a = [3, 7, 4, 8, 6, 2, 1, 5] n = len(a) up = 1 sort(a, n, up) print ("\n\nSorted array is") for i in range(n):     print("%d" %a[i]),
263
# Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module. from collections import defaultdict def grouping_dictionary(l): d = defaultdict(list) for k, v in l: d[k].append(v) return d colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] print("Original list:") print(colors) print("\nGrouping a sequence of key-value pairs into a dictionary of lists:") print(grouping_dictionary(colors))
67
# Find missing numbers in an array arr=[]size = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,size):    num = int(input())    arr.append(num)sum=0for i in range(0,size):    sum += arr[i]size2=size+1miss=int((size2*(size2+1))/2)print("Missing Number is: ",abs(miss-sum))
37
# How to drop one or multiple columns in Pandas Dataframe in Python # Import pandas package  import pandas as pd    # create a dictionary with five fields each data = {     'A':['A1', 'A2', 'A3', 'A4', 'A5'],      'B':['B1', 'B2', 'B3', 'B4', 'B5'],      'C':['C1', 'C2', 'C3', 'C4', 'C5'],      'D':['D1', 'D2', 'D3', 'D4', 'D5'],      'E':['E1', 'E2', 'E3', 'E4', 'E5'] }    # Convert the dictionary into DataFrame  df = pd.DataFrame(data)    df
68
# Sort array in descending order using recursion def swap_Element(arr,i,j):    temp = arr[i]    arr[i] = arr[j]    arr[j] = tempdef Decreasing_sort_element(arr,n):    if(n>0):        for i in range(0,n):            if (arr[i] <= arr[n - 1]):                swap_Element(arr, i, n - 1)        Decreasing_sort_element(arr, n - 1)def printArr(arr,n):    for i in range(0, n):        print(arr[i],end=" ")arr=[]n = int(input("Enter the size of the array: "))print("Enter the Element of the array:")for i in range(0,n):    num = int(input())    arr.append(num)Decreasing_sort_element(arr,n)print("After Decreasing order sort Array Elements are:")printArr(arr, n)
75
# Write a Python program to print Pascal’s Triangle # Print Pascal's Triangle in Python from math import factorial # input n n = 5 for i in range(n):     for j in range(n-i+1):         # for left spacing         print(end=" ")     for j in range(i+1):         # nCr = n!/((n-r)!*r!)         print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")     # for new line     print()
55
# Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array. import numpy as np x = np.array([[0,1],[2,3]]) print("Original array:") print(x) print("Sum of all elements:") print(np.sum(x)) print("Sum of each column:") print(np.sum(x, axis=0)) print("Sum of each row:") print(np.sum(x, axis=1))
51
# Write a Pandas program to change the data type of given a column or a Series. import pandas as pd s1 = pd.Series(['100', '200', 'python', '300.12', '400']) print("Original Data Series:") print(s1) print("Change the said data type to numeric:") s2 = pd.to_numeric(s1, errors='coerce') print(s2)
44
# Write a Python program to append items from inerrable to the end of the array. from array import * array_num = array('i', [1, 3, 5, 7, 9]) print("Original array: "+str(array_num)) array_num.extend(array_num) print("Extended array: "+str(array_num))
35
# Write a Pandas program to split a given dataframe into groups with bin counts. 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], 'customer_id':[3005,3001,3002,3009,3005,3007,3002,3004,3009,3008,3003,3002], 'sales_id':[5002,5003,5004,5003,5002,5001,5005,5007,5008,5004,5005,5001]}) print("Original DataFrame:") print(df) groups = df.groupby(['customer_id', pd.cut(df.sales_id, 3)]) result = groups.size().unstack() print(result)
43
# Write a Python program that takes a text file as input and returns the number of words of a given text file. def count_words(filepath): with open(filepath) as f: data = f.read() data.replace(",", " ") return len(data.split(" ")) print(count_words("words.txt"))
39
# Possible Words using given characters in Python # Function to print words which can be created # using given set of characters          def charCount(word):     dict = {}     for i in word:         dict[i] = dict.get(i, 0) + 1     return dict       def possible_words(lwords, charSet):     for word in lwords:         flag = 1         chars = charCount(word)         for key in chars:             if key not in charSet:                 flag = 0             else:                 if charSet.count(key) != chars[key]:                     flag = 0         if flag == 1:             print(word)    if __name__ == "__main__":     input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']     charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']     possible_words(input, charSet)
102
# Python Program to Check whether 2 Linked Lists are Same class Node: def __init__(self, data): self.data = data self.next = None     class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next     def is_equal(llist1, llist2): current1 = llist1.head current2 = llist2.head while (current1 and current2): if current1.data != current2.data: return False current1 = current1.next current2 = current2.next if current1 is None and current2 is None: return True else: return False     llist1 = LinkedList() llist2 = LinkedList()   data_list = input('Please enter the elements in the first linked list: ').split() for data in data_list: llist1.append(int(data))   data_list = input('Please enter the elements in the second linked list: ').split() for data in data_list: llist2.append(int(data))   if is_equal(llist1, llist2): print('The two linked lists are the same.') else: print('The two linked list are not the same.', end = '')
152
# Write a Python program to create a floating-point representation of the Arrow object, in UTC time using arrow module. import arrow a = arrow.utcnow() print("Current Datetime:") print(a) print("\nFloating-point representation of the said Arrow object:") f = arrow.utcnow().float_timestamp print(f)
39
# Write a Python program to convert timezone from local to utc, utc to local or specified zones. import arrow utc = arrow.utcnow() print("utc:") print(utc) print("\nutc to local:") print(utc.to('local')) print("\nlocal to utc:") print(utc.to('local').to('utc')) print("\nutc to specific location:") print(utc.to('US/Pacific'))
38
# Decimal to Octal conversion using recursion sem=1octal=0def DecimalToOctal(n):    global sem,octal    if(n!=0):        octal = octal + (n % 8) * sem        sem = sem * 10        DecimalToOctal(n // 8)    return octaln=int(input("Enter the Decimal Value:"))print("Octal Value of Decimal number is: ",DecimalToOctal(n))
40
# rite a Python class named Rectangle constructed by a length and width and a method which will compute the area of a rectangle. class Rectangle(): def __init__(self, l, w): self.length = l self.width = w def rectangle_area(self): return self.length*self.width newRectangle = Rectangle(12, 10) print(newRectangle.rectangle_area())
45
# Python Program to Display the Nodes of a Linked List in Reverse without using Recursion class Node: def __init__(self, data): self.data = data self.next = None   class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next   def display_reversed(self): end_node = None   while end_node != self.head: current = self.head while current.next != end_node: current = current.next print(current.data, end = ' ') end_node = current   a_llist = LinkedList() n = int(input('How many elements would you like to add? ')) for i in range(n): data = int(input('Enter data item: ')) a_llist.append(data)   print('The reversed linked list: ', end = '') a_llist.display_reversed()
118
# Write a Python program to sort a given list of lists by length and value. def sort_sublists(input_list): input_list.sort() # sort by sublist contents input_list.sort(key=len) return input_list list1 = [[2], [0], [1, 3], [0, 7], [9, 11], [13, 15, 17]] print("Original list:") print(list1) print("\nSort the list of lists by length and value:") print(sort_sublists(list1))
53
# Program to Find nth Armstrong Number rangenumber=int(input("Enter a Nth Number:")) c = 0 letest = 0 num = 1 while c != rangenumber:     num2 = num     num1 = num     sum = 0     while num1 != 0:         rem = num1 % 10         num1 = num1 // 10         sum = sum + rem * rem * rem     if sum == num2:         c+=1         letest = num     num = num + 1 print(rangenumber,"th Armstrong Number is ",latest)
74
# Write a Python program to wrap an element in the specified tag and create the new wrapper. from bs4 import BeautifulSoup soup = BeautifulSoup("<p>Python exercises.</p>", "lxml") print("Original Markup:") print(soup.p.string.wrap(soup.new_tag("i"))) print("\nNew Markup:") print(soup.p.wrap(soup.new_tag("div")))
33
# Program to check two matrix are equal or not # Get size of 1st matrix row_size=int(input("Enter the row Size Of the 1st Matrix:")) col_size=int(input("Enter the columns Size Of the 1st Matrix:")) # Get size of 2nd matrix row_size1=int(input("Enter the row Size Of the 1st Matrix:")) col_size1=int(input("Enter the columns Size Of the 2nd Matrix:")) matrix=[] # Taking input of the 1st matrix print("Enter the 1st Matrix Element:") for i in range(row_size): matrix.append([int(j) for j in input().split()]) matrix1=[] # Taking input of the 2nd matrix print("Enter the 2nd Matrix Element:") for i in range(row_size): matrix1.append([int(j) for j in input().split()]) # Compare two matrices point=0 if row_size==row_size1 and col_size==col_size1: for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] != matrix1[i][j]: point=1 break else: print("Two matrices are not equal.") exit(0) if point==1: print("Two matrices are not equal.") else: print("Two matrices are equal.")
140
# Write a Python program to create a string representation of the Arrow object, formatted according to a format string. import arrow print("Current datetime:") print(arrow.utcnow()) print("\nYYYY-MM-DD HH:mm:ss ZZ:") print(arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')) print("\nDD-MM-YYYY HH:mm:ss ZZ:") print(arrow.utcnow().format('DD-MM-YYYY HH:mm:ss ZZ')) print(arrow.utcnow().format('\nMMMM DD, YYYY')) print(arrow.utcnow().format())
41
# Write a Python program to remove specific words from a given list. def remove_words(list1, remove_words): for word in list(list1): if word in remove_words: list1.remove(word) return list1 colors = ['red', 'green', 'blue', 'white', 'black', 'orange'] remove_colors = ['white', 'orange'] print("Original list:") print(colors) print("\nRemove words:") print(remove_colors) print("\nAfter removing the specified words from the said list:") print(remove_words(colors, remove_colors))
56
# Python Program to Modify the Linked List such that All Even Numbers appear before all the Odd Numbers in the Modified Linked List class Node: def __init__(self, data): self.data = data self.next = None     class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next   def display(self): current = self.head while current: print(current.data, end = ' ') current = current.next   def get_node(self, index): current = self.head for i in range(index): if current is None: return None current = current.next return current   def get_prev_node(self, ref_node): current = self.head while (current and current.next != ref_node): current = current.next return current   def insert_at_beg(self, new_node): if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node   def remove(self, node): prev_node = self.get_prev_node(node) if prev_node is None: self.head = self.head.next else: prev_node.next = node.next     def move_even_before_odd(llist): current = llist.head while current: temp = current.next if current.data % 2 == 0: llist.remove(current) llist.insert_at_beg(current) current = temp     a_llist = LinkedList()   data_list = input('Please enter the elements in the linked list: ').split() for data in data_list: a_llist.append(int(data))   move_even_before_odd(a_llist)   print('The new list: ') a_llist.display()
198
# Write a Python program to Similar characters Strings comparison # Python3 code to demonstrate working of  # Similar characters Strings comparison # Using split() + sorted()    # initializing strings test_str1 = 'e:e:k:s:g' test_str2 = 'g:e:e:k:s'    # printing original strings print("The original string 1 is : " + str(test_str1)) print("The original string 2 is : " + str(test_str2))    # initializing delim  delim = ':'    # == operator is used for comparison res = sorted(test_str1.split(':')) == sorted(test_str2.split(':'))        # printing result  print("Are strings similar : " + str(res)) 
86
# How to Download All Images from a Web Page in Python from bs4 import * import requests import os    # CREATE FOLDER def folder_create(images):     try:         folder_name = input("Enter Folder Name:- ")         # folder creation         os.mkdir(folder_name)        # if folder exists with that name, ask another name     except:         print("Folder Exist with that name!")         folder_create()        # image downloading start     download_images(images, folder_name)       # DOWNLOAD ALL IMAGES FROM THAT URL def download_images(images, folder_name):          # intitial count is zero     count = 0        # print total images found in URL     print(f"Total {len(images)} Image Found!")        # checking if images is not zero     if len(images) != 0:         for i, image in enumerate(images):             # From image tag ,Fetch image Source URL                            # 1.data-srcset                         # 2.data-src                         # 3.data-fallback-src                         # 4.src                # Here we will use exception handling                # first we will search for "data-srcset" in img tag             try:                 # In image tag ,searching for "data-srcset"                 image_link = image["data-srcset"]                                # then we will search for "data-src" in img              # tag and so on..             except:                 try:                     # In image tag ,searching for "data-src"                     image_link = image["data-src"]                 except:                     try:                         # In image tag ,searching for "data-fallback-src"                         image_link = image["data-fallback-src"]                     except:                         try:                             # In image tag ,searching for "src"                             image_link = image["src"]                            # if no Source URL found                         except:                             pass                # After getting Image Source URL             # We will try to get the content of image             try:                 r = requests.get(image_link).content                 try:                        # possibility of decode                     r = str(r, 'utf-8')                    except UnicodeDecodeError:                        # After checking above condition, Image Download start                     with open(f"{folder_name}/images{i+1}.jpg", "wb+") as f:                         f.write(r)                        # counting number of image downloaded                     count += 1             except:                 pass            # There might be possible, that all         # images not download         # if all images download         if count == len(images):             print("All Images Downloaded!")                        # if all images not download         else:             print(f"Total {count} Images Downloaded Out of {len(images)}")    # MAIN FUNCTION START def main(url):          # content of URL     r = requests.get(url)        # Parse HTML Code     soup = BeautifulSoup(r.text, 'html.parser')        # find all images in URL     images = soup.findAll('img')        # Call folder create function     folder_create(images)       # take url url = input("Enter URL:- ")    # CALL MAIN FUNCTION main(url)
348
# Write a NumPy program to create a new vector with 2 consecutive 0 between two values of a given vector. import numpy as np nums = np.array([1,2,3,4,5,6,7,8]) print("Original array:") print(nums) p = 2 new_nums = np.zeros(len(nums) + (len(nums)-1)*(p)) new_nums[::p+1] = nums print("\nNew array:") print(new_nums)
45
# Write a Python program to find the items that are parity outliers in a given list. from collections import Counter def find_parity_outliers(nums): return [ x for x in nums if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0] ] print(find_parity_outliers([1, 2, 3, 4, 6])) print(find_parity_outliers([1, 2, 3, 4, 5, 6, 7]))
55
# Check if one array is a subset of another array or not arr=[] arr2=[] size = int(input("Enter the size of the 1st array: ")) size2 = int(input("Enter the size of the 2nd array: ")) print("Enter the Element of the 1st array:") for i in range(0,size):     num = int(input())     arr.append(num) print("Enter the Element of the 2nd array:") for i in range(0,size2):     num2 = int(input())     arr2.append(num2) count=0 for i in range(0, size):     for j in range(0, size2):         if arr[i] == arr2[j]:             count+=1 if count==size2:     print("Array two is a subset of array one.") else:     print("Array two is not a subset of array one.")
101
# Write a Pandas program to print the day after and before a specified date. Also print the days between two given dates. import pandas as pd import datetime from datetime import datetime, date today = datetime(2012, 10, 30) print("Current date:", today) tomorrow = today + pd.Timedelta(days=1) print("Tomorrow:", tomorrow) yesterday = today - pd.Timedelta(days=1) print("Yesterday:", yesterday) date1 = datetime(2016, 8, 2) date2 = datetime(2016, 7, 19) print("\nDifference between two dates: ",(date1 - date2))
73
# Write a NumPy program to add two zeros to the beginning of each element of a given array of string values. import numpy as np nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str) print("Original array:") print(nums) print("\nAdd two zeros to the beginning of each element of the said array:") print(np.char.add('00', nums)) print("\nAlternate method:") print(np.char.rjust(nums, 6, fillchar='0'))
57
# Write a NumPy program to fetch all items from a given array of 4,5 shape which are either greater than 6 and a multiple of 3. import numpy as np array_nums1 = np.arange(20).reshape(4,5) print("Original arrays:") print(array_nums1) result = array_nums1[(array_nums1>6) & (array_nums1%3==0)] print("\nItems greater than 6 and a multiple of 3 of the said array:") print(result)
56
# Write a Python program that multiply each number of given list with a given number using lambda function. Print the result. nums = [2, 4, 6, 9 , 11] n = 2 print("Original list: ", nums) print("Given number: ", n) filtered_numbers=list(map(lambda number:number*n,nums)) print("Result:") print(' '.join(map(str,filtered_numbers)))
46
# Write a Pandas program to create a plot of adjusted closing prices, thirty days and forty days simple moving average of Alphabet Inc. between two specific dates. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("alphabet_stock_data.csv") start_date = pd.to_datetime('2020-4-1') end_date = pd.to_datetime('2020-9-30') df['Date'] = pd.to_datetime(df['Date']) new_df = (df['Date']>= start_date) & (df['Date']<= end_date) df1 = df.loc[new_df] stock_data = df1.set_index('Date') close_px = stock_data['Adj Close'] stock_data['SMA_30_days'] = stock_data.iloc[:,4].rolling(window=30).mean() stock_data['SMA_40_days'] = stock_data.iloc[:,4].rolling(window=40).mean() plt.figure(figsize=[10,8]) plt.grid(True) plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to 30-09-2020]\n',fontsize=18, color='black') plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price', color='black') plt.plot(stock_data['SMA_30_days'],label='30 days simple moving average', color='red') plt.plot(stock_data['SMA_40_days'],label='40 days simple moving average', color='green') plt.legend(loc=2) plt.show()
102
# Write a Python program to split values into two groups, based on the result of the given filter list. def bifurcate(colors, filter): return [ [x for x, flag in zip(colors, filter) if flag], [x for x, flag in zip(colors, filter) if not flag] ] print(bifurcate(['red', 'green', 'blue', 'pink'], [True, True, False, True]))
53
# Write a Python program to split a list into different variables. color = [("Black", "#000000", "rgb(0, 0, 0)"), ("Red", "#FF0000", "rgb(255, 0, 0)"), ("Yellow", "#FFFF00", "rgb(255, 255, 0)")] var1, var2, var3 = color print(var1) print(var2) print(var3)
37
# rite a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers that are divisible by 5 in a comma separated sequence. items = [] num = [x for x in input().split(',')] for p in num: x = int(p, 2) if not x%5: items.append(p) print(','.join(items))
56
# Write a NumPy program to test element-wise for positive or negative infinity. import numpy as np a = np.array([1, 0, np.nan, np.inf]) print("Original array") print(a) print("Test element-wise for positive or negative infinity:") print(np.isinf(a))
34
# Write a Python NumPy program to compute the weighted average along the specified axis of a given flattened array. import numpy as np a = np.arange(9).reshape((3,3)) print("Original flattened array:") print(a) print("Weighted average along the specified axis of the above flattened array:") print(np.average(a, axis=1, weights=[1./4, 2./4, 2./4]))
47
# Write a Pandas program to convert a NumPy array to a Pandas series. import numpy as np import pandas as pd np_array = np.array([10, 20, 30, 40, 50]) print("NumPy array:") print(np_array) new_series = pd.Series(np_array) print("Converted Pandas series:") print(new_series)
39
# Write a Python program to find the indexes of all elements in the given list that satisfy the provided testing function. def find_index_of_all(lst, fn): return [i for i, x in enumerate(lst) if fn(x)] print(find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1))
45
# Write a Python program to Sort Dictionary by Values Summation # Python3 code to demonstrate working of  # Sort Dictionary by Values Summation # Using dictionary comprehension + sum() + sorted()    # initializing dictionary test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]}     # printing original dictionary print("The original dictionary is : " + str(test_dict))    # summing all the values using sum() temp1 = {val: sum(int(idx) for idx in key)             for val, key in test_dict.items()}    # using sorted to perform sorting as required temp2 = sorted(temp1.items(), key = lambda ele : temp1[ele[0]])    # rearrange into dictionary res = {key: val for key, val in temp2}            # printing result  print("The sorted dictionary : " + str(res)) 
124
# Python Program to Print Table of a Given Number   n=int(input("Enter the number to print the tables for:")) for i in range(1,11): print(n,"x",i,"=",n*i)
23
# Write a Python program to Numpy np.eigvals() method # import numpy from numpy import linalg as LA    # using np.eigvals() method gfg = LA.eigvals([[1, 2], [3, 4]])    print(gfg)
29
# Program to convert Octal To Hexadecimal i=0 octal=int(input("Enter Octal number:")) Hex=['0']*50 decimal = 0 sem = 0 #Octal to decimal covert while octal!=0:     decimal=decimal+(octal%10)*pow(8,sem);     sem+=1     octal=octal// 10 #Decimal to Hexadecimal while decimal!=0:     rem=decimal%16     #Convert Integer to char     if rem<10:         Hex[i]=chr(rem+48)#48 Ascii=0         i+=1     else:         Hex[i]=chr(rem+55) #55 Ascii=7         i+=1     decimal//=16 print("Hexadecimal number is:") for j in range(i-1,-1,-1):     print(Hex[j],end="")
57
# Write a Python program to remove newline characters from a file. def remove_newlines(fname): flist = open(fname).readlines() return [s.rstrip('\n') for s in flist] print(remove_newlines("test.txt"))
24
# Write a Pandas program to merge two given dataframes with different columns. import pandas as pd data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 'key2': ['K0', 'K1', 'K0', 'K1'], 'P': ['P0', 'P1', 'P2', 'P3'], 'Q': ['Q0', 'Q1', 'Q2', 'Q3']}) data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 'key2': ['K0', 'K0', 'K0', 'K0'], 'R': ['R0', 'R1', 'R2', 'R3'], 'S': ['S0', 'S1', 'S2', 'S3']}) print("Original DataFrames:") print(data1) print("--------------------") print(data2) print("\nMerge two dataframes with different columns:") result = pd.concat([data1,data2], axis=0, ignore_index=True) print(result)
78
# numpy matrix operations | randn() function in Python # Python program explaining # numpy.matlib.randn() function    # importing matrix library from numpy import numpy as geek import numpy.matlib    # desired 3 x 4 random output matrix  out_mat = geek.matlib.randn((3, 4))  print ("Output matrix : ", out_mat) 
46
# Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself. def change_char(str1): char = str1[0] str1 = str1.replace(char, '$') str1 = char + str1[1:] return str1 print(change_char('restart'))
47
# Write a Pandas program to construct a series using the MultiIndex levels as the column and index. import pandas as pd import numpy as np sales_arrays = [['sale1', 'sale1', 'sale2', 'sale2', 'sale3', 'sale3', 'sale4', 'sale4'], ['city1', 'city2', 'city1', 'city2', 'city1', 'city2', 'city1', 'city2']] sales_tuples = list(zip(*sales_arrays)) print("Create a MultiIndex:") sales_index = pd.MultiIndex.from_tuples(sales_tuples, names=['sale', 'city']) print(sales_tuples) print("\nConstruct a series using the said MultiIndex levels: ") s = pd.Series(np.random.randn(8), index = sales_index) print(s)
72
# Write a Python program to test if a variable is a list or tuple or a set. #x = ['a', 'b', 'c', 'd'] #x = {'a', 'b', 'c', 'd'} x = ('tuple', False, 3.2, 1) if type(x) is list: print('x is a list') elif type(x) is set: print('x is a set') elif type(x) is tuple: print('x is a tuple') else: print('Neither a list or a set or a tuple.')
70
# Write a NumPy program to replace the negative values in a NumPy array with 0. import numpy as np x = np.array([-1, -4, 0, 2, 3, 4, 5, -6]) print("Original array:") print(x) print("Replace the negative values of the said array with 0:") x[x < 0] = 0 print(x)
49
# Compute the covariance matrix of two given NumPy arrays in Python import numpy as np       array1 = np.array([0, 1, 1]) array2 = np.array([2, 2, 1])    # Original array1 print(array1)    # Original array2 print(array2)    # Covariance matrix print("\nCovariance matrix of the said arrays:\n",       np.cov(array1, array2))
45
# Write a NumPy program to find the real and imaginary parts of an array of complex numbers. import numpy as np x = np.sqrt([1+0j]) y = np.sqrt([0+1j]) print("Original array:x ",x) print("Original array:y ",y) print("Real part of the array:") print(x.real) print(y.real) print("Imaginary part of the array:") print(x.imag) print(y.imag)
48
# Write a Pandas program to join the two dataframes using the common column of both dataframes. import pandas as pd student_data1 = pd.DataFrame({ 'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'], 'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'], 'marks': [200, 210, 190, 222, 199]}) student_data2 = pd.DataFrame({ 'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'], 'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'], 'marks': [201, 200, 198, 219, 201]}) print("Original DataFrames:") print(student_data1) print(student_data2) merged_data = pd.merge(student_data1, student_data2, on='student_id', how='inner') print("Merged data (inner join):") print(merged_data)
88
# Write a Python program to get the file size of a plain file. def file_size(fname): import os statinfo = os.stat(fname) return statinfo.st_size print("File size in bytes of a plain file: ",file_size("test.txt"))
32
# Write a Python program to check whether a specified list is sorted or not using lambda. def is_sort_list(nums, key=lambda x: x): for i, e in enumerate(nums[1:]): if key(e) < key(nums[i]): return False return True nums1 = [1,2,4,6,8,10,12,14,16,17] print ("Original list:") print(nums1) print("\nIs the said list is sorted!") print(is_sort_list(nums1)) nums2 = [2,3,8,4,7,9,8,2,6,5,1,6,1,2,3,4,6,9,1,2] print ("\nOriginal list:") print(nums1) print("\nIs the said list is sorted!") print(is_sort_list(nums2))
63
# Write a Python program to check multiple keys exists in a dictionary. student = { 'name': 'Alex', 'class': 'V', 'roll_id': '2' } print(student.keys() >= {'class', 'name'}) print(student.keys() >= {'name', 'Alex'}) print(student.keys() >= {'roll_id', 'name'})
35
# Write a NumPy program to create an array of zeros and three column types (integer, float, character). import numpy as np x = np.zeros((3,), dtype=('i4,f4,a40')) new_data = [(1, 2., "Albert Einstein"), (2, 2., "Edmond Halley"), (3, 3., "Gertrude B. Elion")] x[:] = new_data print(x)
45
# Write a Python program to convert a given string to camelcase. from re import sub def camel_case(s): s = sub(r"(_|-)+", " ", s).title().replace(" ", "") return ''.join([s[0].lower(), s[1:]]) print(camel_case('JavaScript')) print(camel_case('Foo-Bar')) print(camel_case('foo_bar')) print(camel_case('--foo.bar')) print(camel_case('Foo-BAR')) print(camel_case('fooBAR')) print(camel_case('foo bar'))
37