Found 26504 Articles for Server Side Programming

Python - Add a new column with constant value to Pandas DataFrame

AmitDiwan
Updated on 22-Sep-2021 11:41:48

5K+ Views

To add anew column with constant value, use the square bracket i.e. the index operator and set that value.At first, import the required library −import pandas as pdCreating a DataFrame with 4 columns −dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BBMW', 'Mustang', 'Mercedes', 'Jaguar'], "Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000], "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], "Units_Sold": [ 100, 110, 150, 80, 200, 90] })Adding a new column with a constant value. The new column names is set in the square bracket −dataFrame['Mileage'] = 15 ExampleFollowing is the complete code −import pandas as pd # creating dataframe dataFrame = ... Read More

Python - Check if Pandas dataframe contains infinity

AmitDiwan
Updated on 22-Sep-2021 11:32:31

8K+ Views

To check, use the isinf() method. To find the count of infinite values, use sum(). At first, let us import the required libraries with their respective aliases −import pandas as pd import numpy as npCreate a dictionary of list. We have set the infinity values using the Numpy np.inf −d = { "Reg_Price": [7000.5057, np.inf, 5000, np.inf, 9000.75768, 6000] } Creating dataframe from the above dictionary of listdataFrame = pd.DataFrame(d)Checking for infinite values using isinf() and displaying the countcount = np.isinf(dataFrame).values.sum() ExampleFollowing is the code −import pandas as pd import numpy as np # dictionary of list d = ... Read More

Create a Pivot Table with multiple columns – Python Pandas

AmitDiwan
Updated on 22-Sep-2021 11:25:14

2K+ Views

We can create a Pivot Table with multiple columns. To create a Pivot Table, use the pandas.pivot_table to create a spreadsheet-style pivot table as a DataFrame.At first, import the required library −import pandas as pdCreate a DataFrame with Team records −dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 }, 'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'}, 'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55}, 'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: ... Read More

Python - Calculate the minimum of column values of a Pandas DataFrame

AmitDiwan
Updated on 22-Sep-2021 11:14:09

560 Views

To get the minimum of column values, use the min() function. At first, import the required Pandas library −import pandas as pdNow, create a DataFrame with two columns −dataFrame1 = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )Finding the minimum value of a single column “Units” using min() −print"Minimum Units from DataFrame1 = ", dataFrame1['Units'].min() In the same way, we have calculated the minimum value from the 2nd DataFrame.ExampleFollowing is the complete code −import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame(    { ... Read More

How to exponentially scale the Y axis with matplotlib?

Rishikesh Kumar Rishi
Updated on 21-Sep-2021 10:56:42

4K+ Views

To exponentially scale the Y-axis with matplotlib, we can take the following steps −Set the figure size and adjust the padding between and around the subplots.Inintialize a variable dt for steps.Create x and y data points using numpy.Plot the x and y data points using numpy.Set the exponential scale for the Y-axis, using plt.yscale('symlog').To display the figure, use show() method.Exampleimport numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True dt = 0.01 x = np.arange(-50.0, 50.0, dt) y = np.arange(0, 100.0, dt) plt.plot(x, y) plt.yscale('symlog') plt.show()OutputIt will produce the following ... Read More

Python - Convert List of lists to List of Sets

AmitDiwan
Updated on 21-Sep-2021 08:29:02

835 Views

When it is required to convert a list of list to a list of set, the ‘map’, ‘set’, and ‘list’ methods are used.ExampleBelow is a demonstration of the samemy_list = [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]] print("The list of lists is: ") print(my_list) my_result = list(map(set, my_list)) print("The resultant list is: ") print(my_result)OutputThe list of lists is: [[2, 2, 2, 2], [1, 2, 1], [1, 2, 3], [1, 1], [0]] The resultant list is: [set([2]), set([1, 2]), set([1, 2, 3]), set([1]), set([0])]ExplanationA list of list is defined and is displayed ... Read More

Python program to get all subsets having sum s

AmitDiwan
Updated on 21-Sep-2021 08:27:19

711 Views

When it is required to get all the subset having a specific sum ‘s’, a method is defined that iterates through the list and gets all combinations of the list, and if it matches the sum, it is printed on the console.ExampleBelow is a demonstration of the samefrom itertools import combinations def sub_set_sum(size, my_array, sub_set_sum):    for i in range(size+1):       for my_sub_set in combinations(my_array, i):          if sum(my_sub_set) == sub_set_sum:           print(list(my_sub_set)) my_size = 6 my_list = [21, 32, 56, 78, 45, 99, 0] ... Read More

Python - Filter Rows Based on Column Values with query function in Pandas?

AmitDiwan
Updated on 21-Sep-2021 08:30:34

680 Views

To filter rows based on column values, we can use the query() function. In the function, set the condition through which you want to filter records. At first, import the required library −import pandas as pdFollowing is our data with Team Records −Team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75], ['New Zealand', 4 , 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]Create a DataFrame from above and add columns as well −dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points']) Use query() to filter records with “Rank” equal to 5 −dataFrame.query("Rank == 5"))ExampleFollowing is the complete code −import pandas as ... Read More

Python - Find all the strings that are substrings to the given list of strings

AmitDiwan
Updated on 21-Sep-2021 08:24:09

581 Views

When it is required to find all the strings that are substrings of a given list of strings, the ‘set’ and ‘list’ attributes are used.ExampleBelow is a demonstration of the samemy_list_1 = ["Hi", "there", "how", "are", "you"] my_list_2 = ["Hi", "there", "how", "have", "you", 'been'] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = list(set([elem_1 for subset_1 in my_list_1 for elem_1 in my_list_2 if elem_1 in subset_1])) print("The result is :") print(my_result)OutputThe first list is : ['Hi', 'there', 'how', 'are', 'you'] The second list is : ['Hi', 'there', 'how', 'have', 'you', 'been'] The ... Read More

Python program to print sorted number formed by merging all elements in array

AmitDiwan
Updated on 21-Sep-2021 08:22:06

220 Views

When it is required to print the sorted numbers that are formed by merging the elements of an array, a method can be defined that first sorts the number and converts the number to an integer. Another method maps this list to a string, and is sorted again.ExampleBelow is a demonstration of the samedef get_sorted_nums(my_num): my_num = ''.join(sorted(my_num)) my_num = int(my_num) print(my_num) def merged_list(my_list): my_list = list(map(str, my_list)) my_str = ''.join(my_list) get_sorted_nums(my_str) my_list = [7, 845, 69, 60, ... Read More

Advertisements