How to Move a File in Python

Here are 3 ways to move a file in Python Using the “os.rename()” function Using the “shutil.move()” function Using the “pathlib.Path()” If the file is not found in the provided path, it will return the FileError. Method 1: Using the os.rename() function The os.rename() renames the file or directory src to dist. The rename() can … Read more

How to Compare Values of Two DataFrames in Pandas

Here are two ways to compare values of two DataFrames in Pandas: Using numpy.where() method Using DataFrame.compare() method Method 1: Using numpy.where() method To compare the values of two DataFrames in Pandas, you can use the “numpy.where()” method. Syntax df1[‘new column for the comparison results’] = np.where(condition, ‘value if true’, ‘value if false’) Example import pandas … Read more

What is the numpy.ndarray.flat() Method

Numpy.ndarray.flat() function is “used as a 1D iterator over N-dimensional arrays”. It is not a subclass of Python’s built-in iterator object; otherwise, it is a numpy.flatiter instance. Syntax ndarray.flat(range) Parameters range: Indicates the range in which we want to print values. Return Value The ndarray flat() function returns a 1D iteration of the given ndarray. … Read more

What is the numpy vdot() Method

Numpy.vdot() method “returns the dot product of two vectors”. If the first argument is complex, its conjugate is used for calculation. If the argument id is a multi-dimensional array, it is flattened. Syntax numpy.vdot(Vect_A, Vect_B) Parameters The vdot() function takes up to two main parameters: Vect_A: array-like, if Vect_A is complex, then it uses a … Read more

What is the numpy.trunc() Method

Numpy.trunc() method “returns the truncated value of the elements of the array.” The trunc of the scalar x is the nearest integer i, which is closer to zero than x. Syntax numpy.trunc(arr[, out]) = ufunc ‘trunc’) Parameters The trunc() method takes up to two parameters: arr: This is an array whose elements are to be … Read more

What is the numpy.isscalar() Method in Python

Numpy isscalar() method “returns True if the input element is a scalar type.” Syntax numpy.isscalar(input_number) Parameters input_number: It is the input value for which we want to test whether it is a scalar value. Return Value The isscalar() method returns a Boolean value, which is true if the input value is scalar and False otherwise. Example … Read more

How to Connect Python to MySQL using PyMySQL

To connect Python3 to MySQL, you need to install the “pymysql” package and use the “connect()” method. The connect() method is used to establish a connection to the MySQL database and accepts several arguments. In Python, connecting to any database server sometimes makes troublesome because Python has two main versions: Python 2 and Python 3. So, … Read more

Python shutil.copy() Method

The shutil.copy() method is “used to copy the content of source file to destination file or directory”. It also preserves the file’s permission mode but other metadata, like the file’s creation and modification times, is not preserved. Syntax shutil.copy(source, destination, *, follow_symlinks = True) Parameters source: It is a string representing the path of the source file.  destination: It is … Read more

How to Convert Degrees to Radians in Python

To convert degrees to radians in Python, you can use the “numpy.radians()” method. This means if we provide any value in degree, this function will help us to convert it into radian. Syntax numpy.radians(arr[, out]) = ufunc ‘radians’) Parameters The radians() function takes up to two main parameters: arr: This is the array whose elements … Read more

Pandas Iterate Over Columns of DataFrame

Here are the 6 ways to iterate over columns of DataFrame: Using the [] operator Using for loop with items() Using iteritems() Using enumerate() Using DataFrame.columns() Using transpose().iterrows() Method 1: Using the [ ] operator We can iterate over column names using the [] operator. Example import pandas as pd # Create a sample DataFrame … Read more

What is the numpy.npv() Method

Numpy.npv() method is “used to calculate the NPV(Net Present Value) of a cash flow series.” Syntax numpy.npv(rate, values) Parameters rate: This indicates the rate of the discount. values: The values of the time series of cash flows. The (fixed) period between cash flow “events” must be the same as that for which the rate is … Read more

What is the numpy.eye() Method

Numpy.eye() method “returns a 2D array with  1’s as the diagonal and  0’s elsewhere.” The diagonal can be main, upper, or lower depending on the optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a  0 k (default) is for the main diagonal. Syntax numpy.eye(N, M=None, k=0, dtype=<class ‘float’>, order=’C’) Parameters N: It … Read more

What is the numpy.place() Method in Python

The numpy.place() method “makes changes in the array according to the parameters – conditions, and value(uses first N-values to put into an array as per the mask being set by the user)”. Syntax numpy.place(array, mask, vals) Parameters array: This depicts the input array in which changes must be made. mask: It describes the Boolean condition. … Read more

What is the numpy.extract() Method

Numpy.extract() method “returns elements of input_array if they satisfy some specified condition.” Syntax numpy.extract (condition, array) Parameters array: It depicts the input array in which the user applies the condition. condition: It shows the condition based on which the user extracts elements. On Applying the condition on the array, if we print the condition, it … Read more

What is the numpy.compress() Method

Numpy.compress() method “returns selected slices of an array along the mentioned axis that satisfies an axis.” Syntax numpy.compress (condition, input_array, axis = None, out = None) Parameters condition: It depicts the condition based on which the user extracts elements. On applying a condition to the input_array, it returns an array filled with either True or … Read more

What is the numpy empty_like() Method

Numpy.empty_like() method “returns a new array with the same shape and type as a given array”. Syntax numpy.empty_like(shape, order, dtype, subok) Parameters It takes four parameters, out of which 2 parameters are optional.  shape: It represents the number of rows.  order: It represents the order in the memory. (C_contiguous or F_contiguous).  dtype: It’s the data … Read more

Numpy.put() Method

Numpy.put() method is “used to replace specific elements of an array with given values of p_array.” Array indexed works on a flattened array. Syntax numpy.put(array, indices, values, mode) Parameters The NumPy put() function can take up to 4 parameters. array: It is the array in which we want to work indices: Index of the values … Read more

How to Use the numpy.asmatrix() Method

Numpy.asmatrix() method is “used to interpret the input as a matrix”. If the input is already a matrix or a ndarray of 2 dimensions, it returns the input as is. If the input is a different data type, such as a list or a tuple, it converts it into a matrix. Syntax numpy.asmatrix(data, dtype=None) Parameters … Read more

Pandas.DataFrame.filter() Method in Python

Pandas Dataframe filter() method is “used to filter the DataFame rows and columns.” The returned DataFrame contains only rows and columns specified by the function. Syntax DataFrame.filter(self: ~FrameOrSeries, items=None, like: Union[str, NoneType] = None, regex: Union[str, NoneType] = None, axis=None) Parameters items: list-like Keep labels from the axis that are in items. like: str Keep labels … Read more

Pandas DataFrame assign() Method

Pandas DataFrame assign() method is “used to assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones.” Syntax DataFrame.assign(**kwargs) Parameters **kwargs: dict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and … Read more

What is the numpy.delete() Method

Numpy.delete() method “returns a new array with the deletion of sub-arrays along with the mentioned axis.” Syntax numpy.delete(array, object, axis = None) Parameters The np.delete() function takes three parameters: array: This is the input array. object: This can be any single number or a subarray. axis: This indicates the axis to be deleted from the … Read more

Python math.gamma() Function

Python math.gamma() method is “used to calculate the gamma value of the number passed in the function.” The gamma value equals the factorial(x-1) number passed as a parameter. Syntax math.gamma(var) Parameters var: It is a numeric datatype and throws TypeError if the argument of any other data type is passed. Return Value It returns the … Read more

Python math.erfc() Method

Python math.erfc() method “returns the complementary error function of the argument.” Syntax math.erfc(var) Parameters var: It is a numeric data type and throws TypeError if the argument of any other data type is passed. Return Value It returns the error function value of the number in the float datatype. Example 1: How to Use math.erfc() Method … Read more

Python Math.erf() Method

Python erf() method is “used to print error functions for numbers.” For example, if x is passed as a parameter in the erf function (erf(x)), it returns the error function. Syntax math.erf(var) Parameters var: It takes values of numeric datatype and throws TypeError if an argument is of any other data type is passed. Return Value … Read more

Python math.radians() Method

Python math.radians() method is “used to convert a degree value into radians.” The conversion formula is radians = degrees * (π / 180). Syntax math.radians(degrees) Parameters degrees: The angle in degrees to be converted to radians. Return value It returns a float value, representing the radian value of an angle. Example 1: How does the … Read more

Python math.tanh() Method

Python math.tanh() method “returns the hyperbolic tangent value of a number.” Syntax math.tanh(var) Parameters var: It takes values of numeric datatype and throws a TypeError if the argument of any other data type is passed. Return Value It returns the hyperbolic tangent value of the number in the float datatype. If the number argument is … Read more

Python math.sinh() Method

Python math.sinh() method is “used to return the hyperbolic sine value of a number.” It returns the hyperbolic sine of a number in radians. Syntax math.sinh(var) Parameters var: It takes values of numeric datatype and throws TypeError if an argument of any other data type is passed. Return Value The sinh() function returns a hyperbolic sine … Read more

What is the math.cosh() Method in Python

Python math.cosh() function “returns the hyperbolic cosine of a number.” To be more specific, it returns the hyperbolic cosine of a number in the radians. Syntax math.cosh(var) Parameters var: It takes values of numeric datatype and throws TypeError if an argument of any other data type is passed. Return value The cosh() returns the hyperbolic cosine of … Read more

Python math.degrees() Method

Python math.degrees() method is “used to convert the radian value to degrees.” Syntax math.degrees(var) Parameters var: It takes values of numeric datatype and throws a type error if an argument of any other data type is passed. Return Value It returns the degree value of the number in the float datatype. Example 1: How to Use math.degrees() Method … Read more

Python Math.hypot() Method

Python math.hypot() method “returns the Euclidean norm.” The Euclidian norm is the distance from the origin to the coordinates given. Syntax math.hypot(a,b) Parameters a, b: They are numbers we will use to find the Euclidean form. If any other type of value is passed ( suppose char), then it will throw a type error. Return Value … Read more

Python math.atan() Method

Python math.atan() method “returns the arctangent of a number as a value.” The value passed to the atan() method should be between -PI/2 and PI/2 radians. Syntax math.atan(var) Parameters var: This parameter is the value passed to atan(). Any other data type is not acceptable. If any other data type is passed as a parameter, it throws … Read more

Python math.asin() Method

Python math.asin() method “returns the arc sine value of a number.” The returned result is in radians and will be in the range of -π/2 to π/2. The parameter passed in math.asin() must lie between -1 to 1. Syntax math.asin(num) Parameters num: It takes values from the range -1 to 1 and throws and value error … Read more

Python math.exp() Method

Python math.exp() method is “used to calculate the power of e i.e. e^y, or we can say exponential of y.” The value of e is approximately equal to 2.71828. Syntax math.exp(num) Parameters num: The function takes only one argument num, which we want to find exponential. Return Value The math.exp() method returns a floating type … Read more

Python math.trunc() Method

Python math.trunc() method “returns the truncated integer part of a number.” For example, if the number is 3.14, the math.trunc() method will return 3. Syntax math.trunc(x) Parameters x: The number to be truncated. Return value It returns the truncated integer part of x. Time Complexity: O(1) Auxiliary Space: O(1) Example: How to Use math.trunc() Method import math … Read more

How to Use If, Else and Elif in Lambda Functions in Python

The anonymous functions are defined using a lambda keyword. The lambda function can have multiple parameters but only one expression. Using if-else in lambda function The lambda method “returns a value for every validated input.” In this case, if block will be returned when the condition is true, and else block will be returned when the … Read more

Python math.isinf() Method

Python math.isinf() method is “used to check whether a number is infinite.” Syntax math.isinf(n) The isinf() function takes n as an argument and checks whether n is infinite. Parameters Here n can be an integer, float, double, inf, NaN, etc. Return Value The math.isinf() function returns two types of output: True: If the number is … Read more

How to Remove Rows from DataFrame in Pandas

Here are five ways to remove rows from DataFrame in Python: Using drop() method Using boolean indexing Using the query() method Using the iloc[] indexer Using the drop() method with the index attribute Method 1: Using the drop() method To remove single or multiple rows from a DataFrame in Pandas, you can use the drop() method … Read more

How to Remove an Element From Dictionary in Python

Here are the ways to remove an element from a dictionary in Python: Using the “del” statement Using the “dict.pop()” method Using the “popitem()” method Using the “clear()” method Method 1: Using the “del” statement To remove an element from a dictionary using the del statement, “specify the key of the element you want to … Read more

Python Tuple count() Method (With Examples)

Python tuple count() method  “returns the number of times the specified element appears in the tuple.” Syntax tuple.count(element) Parameters “element”: It is an element to count in the tuple. Return Value Python tuple count() method returns the number of occurrences of one element in the tuple. Example 1: How to Use tuple.count() Method # Declaring … Read more

How to Access Characters in String by Index in Python

To access characters in a string by index in Python, you can “use the square brackets []” along with the index number to access a specific character. String indexing in Python is zero-based: the first character in the string has index 0, the next has index 1, and so on. str = ‘Millie Bobby Brown’ … Read more

How to Convert Python Dictionary to CSV File

To convert a dictionary to csv in Python, you can use the “csv.DictWriter()” method. The DictWriter() method is used to create an object which operates like the regular writer but maps the dictionaries onto output rows. CSV (comma-separated values) files are one of the easiest ways to transfer data in strings, especially for any spreadsheet … Read more

Python String center() Method

Python String center() method returns a new string, centered by padding it with the specified character(default is space) until it reaches a given width. Syntax string.center(width, fillchar) Parameters width(required): length of the string with padded characters. fillchar(optional):  The character to fill the padding. The default is a space. Return value It returns a new string … Read more

Python any() Function

Python any() function “returns True if any element of an iterable is True. If not, it returns False.” Syntax any(iterable) Parameters iterable: The any() function takes an iterable (list, string, dictionary, etc.) in Python. Return value The any() function returns the following values: True if at least one item of an iterable is True. False … Read more

Python hash() Method

Python hash() method “returns the hash value of an object if it has one.” Hash values are just integers used to quickly compare dictionary keys during a dictionary look. Syntax hash(object) Parameters object: It is a hash value that will be returned (integer, string, float). Return value The hash() method returns the hash value of … Read more

Python Dictionary get() Method

Python Dictionary get() method “returns the value of the specified key if the key is in the dictionary, otherwise it returns None (or a specified default value).“ Syntax dictionary.get(keyname, value) Parameters The keyname name parameter and the keyname of the item you want to return the value are required. The value parameter is Optional. It … Read more

Python String count() Method

Python String count() method is used to count how many times a specified value (substring) appears in a string. Syntax string.count(substring, start, end) Parameters substring(required): It is the substring to search for.  start(optional): It is the starting index within the string where the search starts(Default 0).  end(optional): It is the ending index within the string … Read more

Pandas Series value_counts() Method

Pandas Series value_counts() method “returns a Series containing counts of unique values.” The resulting object will be in descending order, so the first element is the most frequently-occurring element. It excludes NA values by default. Syntax Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True) Parameters normalize: boolean, default False. If True, the object returned will contain the relative … Read more