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', 'ci...
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)] ...
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 ...
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) fo...
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 ...
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...
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_...
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...
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'],         ['GeeksforG...
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_d...
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 ...
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 digit...
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_...
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:") pr...
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().in...
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) ...
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 t...
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,7000...
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:"...
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("\nC...
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:") prin...
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.*/ de...
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',...
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-...
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',...
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(ar...
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)/...
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...
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....
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:       ...
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: ...
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/P...
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 = Rectan...
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): ...
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...
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 ...
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 c...
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(arro...
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', 'or...
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 ...
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 : " + ...
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 na...
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_...
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 El...
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:", tom...
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:") p...
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 th...
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,filter...
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_...
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, Tru...
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(...
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=...
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...
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 ...
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']}) d...
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']] sal...
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('...
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, ar...
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....
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':...
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) ...
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')...
37