Found 33676 Articles for Programming

Python Pandas - Sort DataFrame in ascending order according to the element frequency

AmitDiwan
Updated on 20-Sep-2021 12:18:01

861 Views

To sort data in ascending or descending order, use sort_values() method. For ascending order, use the following is the sort_values() method −ascending=TrueImport the required library −import pandas as pd Create a DataFrame with 3 columns −dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'], "Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000], "Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh'] } ) To sort DataFrame in ascending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for asscending order sort −dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ... Read More

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

AmitDiwan
Updated on 20-Sep-2021 12:02:38

527 Views

To get the maximum of column values, use the max() 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 maximum value of a single column “Units” using max() −print"Maximum Units from DataFrame1 = ", dataFrame1['Units'].max()In the same way, we have calculated the maximum value from the 2nd DataFrame.ExampleFollowing is the complete code −import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame(    {   ... Read More

How to display Pandas Dataframe in Python without Index?

AmitDiwan
Updated on 20-Sep-2021 11:37:38

4K+ Views

Use index=False to ignore index. Let us first import the required library −import pandas as pdCreate a DataFrame −dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]], index=['x', 'y', 'z'], columns=['a', 'b'])Select rows by passing label using loc −dataFrame.loc['x'] Display DataFrame without index −dataFrame.to_string(index=False)ExampleFollowing is the code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]], index=['x', 'y', 'z'], columns=['a', 'b']) # DataFrame print"Displaying DataFrame with index...", dataFrame # select rows with loc print"Select rows by passing label..." print(dataFrame.loc['x']) # display DataFrame without index print"Displaying DataFrame without Index...", dataFrame.to_string(index=False)OutputThis will produce ... Read More

Python program to sort Palindrome Words in a Sentence

AmitDiwan
Updated on 20-Sep-2021 11:45:10

467 Views

When it is required to sort the palindrome words present in a sentence, a method is defined that takes a string as a parameter and first ensures that it is a palindrome. Then it sorts all the words of a string and returns it as output.ExampleBelow is a demonstration of the samedef check_palindrome(my_string): if(my_string == my_string[::-1]): return True else: return False def print_sort_palindromes(my_sentence): my_list = [] my_result = list(my_sentence.split()) for ... Read More

Python - Generate all possible permutations of words in a Sentence

AmitDiwan
Updated on 20-Sep-2021 11:41:10

868 Views

When it is required to generate all possible permutations of a word in a sentence, a function is defined. This function iterates over the string and depending on the condition, the output is displayed.ExampleBelow is a demonstration of the samefrom itertools import permutations def calculate_permutations(my_string):    my_list = list(my_string.split())    permutes = permutations(my_list)    for i in permutes:       permute_list = list(i)       for j in permute_list:          print j print() my_string = "hi there" print("The string is :") print(my_string) ... Read More

Python program to extract rows from Matrix that has distinct data types

AmitDiwan
Updated on 20-Sep-2021 11:30:04

186 Views

When it is required to extract rows from a matrix with different data types, it is iterated over and ‘set’ is used to get the distinct types.ExampleBelow is a demonstration of the samemy_list = [[4, 2, 6], ["python", 2, {6: 2}], [3, 1, "fun"], [9, (4, 3)]] print("The list is :") print(my_list) my_result = [] for sub in my_list: type_size = len(list(set([type(ele) for ele in sub]))) if len(sub) == type_size: my_result.append(sub) print("The resultant distinct data type rows are :") print(my_result)OutputThe list is : [[4, ... Read More

Python - Split list into all possible tuple pairs

AmitDiwan
Updated on 20-Sep-2021 11:26:05

403 Views

When it is required to split the list into all the possible tuple pairs, a method can be defined that takes a list as a parameter and uses list comprehension to iterate through the list and use ‘extend’ methodExampleBelow is a demonstration of the samedef determine_pairings(my_list): if len(my_list)

Python program to Reverse a range in list

AmitDiwan
Updated on 20-Sep-2021 11:24:18

192 Views

When it is required to reverse a given range in a list, it is iterated over and the ‘:’ operator along with slicing is used to reverse it.ExampleBelow is a demonstration of the samemy_list = ["Hi", "there", "how", 'are', 'you'] print("The list is : ") print(my_list) m, n = 2, 4 my_result = [] for elem in my_list: my_result.append(elem[m : n + 1]) print("The sliced strings are : " ) print(my_result)OutputThe list is : ['Hi', 'there', 'how', 'are', 'you'] The sliced strings are : ['', 'ere', 'w', 'e', 'u']ExplanationA list is defined, and ... Read More

Python - Cumulative Mean of Dictionary keys

AmitDiwan
Updated on 20-Sep-2021 11:22:02

299 Views

When it is required to find the cumulative mean of the dictionary keys, an empty dictionary is created, and the original dictionary is iterated over, and the items are accessed. If this is present in the dictionary, the key is appended to the empty dictionary, otherwise the value is placed instead of the key.ExampleBelow is a demonstration of the samefrom statistics import mean my_list = [{'hi' : 24, 'there' : 81, 'how' : 11}, {'hi' : 16, 'how' : 78, 'doing' : 63}] print("The list is : ") print(my_list) my_result = dict() for sub ... Read More

Python - How to fill NAN values with mean in Pandas?

AmitDiwan
Updated on 20-Sep-2021 11:21:47

5K+ Views

For mean, use the mean() function. Calculate the mean for the column with NaN and use the fillna() to fill the NaN values with the mean.Let us first import the required libraries −import pandas as pd import numpy as npCreate a DataFrame with 2 columns and some NaN values. We have entered these NaN values using numpy np.NaN −dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'Lexus', 'Mustang', 'Bentley', 'Mustang'], "Units": [100, 150, np.NaN, 80, np.NaN, np.NaN] } )Finding mean of the column values with NaN i.e, for Units columns here. So, the Units ... Read More

Advertisements