Found 26504 Articles for Server Side Programming

Python – Stacking a single-level column with Pandas stack()?

AmitDiwan
Updated on 21-Sep-2021 08:05:36

485 Views

To stack a single-level column, use the datafrem.stack(). At first, let us import the required library −import pandas as pdCreate a DataFrame with single-level column −dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b'])Stack the DataFrame using the stack() method −dataFrame.stack() ExampleFollowing is the complete code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b']) # DataFrame print"DataFrame...", dataFrame # stack print"Stacking...", dataFrame.stack()OutputThis will produce the following output −DataFrame...     a   b w  10 ... Read More

Python program to Flatten Nested List to Tuple List

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

352 Views

When it is required to flatten a nested list into a tuple list, a method is defined that takes a list as a parameter, and uses the ‘isinstance’ method to check if an element belongs to a specific type. Depending on this, the output is displayed.ExampleBelow is a demonstration of the samedef convert_nested_tuple(my_list): for elem in my_list: if isinstance(elem, list): convert_nested_tuple(elem) else: my_result.append(elem) return ... Read More

Python - Create nested list containing values as the count of list items

AmitDiwan
Updated on 21-Sep-2021 08:00:49

236 Views

When it is required to create a nested list containing values as the count of list elements, a simple iteration is used.ExampleBelow is a demonstration of the samemy_list = [11, 25, 36, 24] print("The list is :") print(my_list) for element in range(len(my_list)): my_list[element] = [element+1 for j in range(element+1)] print("The resultant list is :") print(my_list)OutputThe list is : [11, 25, 36, 24] The resultant list is : [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]ExplanationA list is defined and is displayed on the console.It is iterated over, and it is added to 1 and ... Read More

Python - How to access the last element in a Pandas series?

AmitDiwan
Updated on 21-Sep-2021 08:01:38

778 Views

We will be using the iat attribute to access the last element, since it is used to access a single value for a row/column pair by integer position.Let us first import the required Pandas library −import pandas as pdCreate a Pandas series with numbers −data = pd.Series([10, 20, 5, 65, 75, 85, 30, 100])Now, get the last element using iat() −data.iat[-1]ExampleFollowing is the code −import pandas as pd # pandas series data = pd.Series([10, 20, 5, 65, 75, 85, 30, 100]) print"Series...", data # get the first element print"The first element in the series = ", data.iat[0] ... Read More

Python - Count the frequency of matrix row length

AmitDiwan
Updated on 21-Sep-2021 07:58:38

221 Views

When it is required to count the frequency of the matrix row length, it is iterated over and its frequency is added to the empty dictionary or incremented if found again.ExampleBelow is a demonstration of the samemy_list = [[42, 24, 11], [67, 18], [20], [54, 10, 25], [45, 99]] print("The list is :") print(my_list) my_result = dict() for element in my_list: if len(element) not in my_result: my_result[len(element)] = 1 else: my_result[len(element)] += 1 print("The result is :") print(my_result)OutputThe ... Read More

Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?

AmitDiwan
Updated on 21-Sep-2021 09:11:43

779 Views

To rename multiple column headers, use the rename() method and set the dictionary in the columns parameter. At first, let us create a DataFrame −dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'], "Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000], "Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500], "Units Sold": [ 200, 120, 150, 120, 210, 250, 220] })Creating a dictionary to rename columns. The key and value pairs as old name and new name −dictionary = {'Car': 'Car Name', 'Cubic Capacity': 'CC', 'Reg Price': 'Registration Price', 'Units Sold': 'Units Purchased' }Use rename() and set the ... Read More

Python - Select columns with specific datatypes

AmitDiwan
Updated on 21-Sep-2021 07:45:55

198 Views

To select columns with specific datatypes, use the select_dtypes() method and the include parameter. At first, create a DataFrame with 2 columns −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } )Now, select the 2 columns with their respective specific datatype −column1 = dataFrame.select_dtypes(include=['object']).columns column2 = dataFrame.select_dtypes(include=['int64']).columnsExampleFollowing is the code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Roll Number": [ 5, 10, ... Read More

Python – Get the datatypes of columns

AmitDiwan
Updated on 21-Sep-2021 07:47:06

152 Views

To get the datatypes of columns, use the info() method. Let us first import the required library −import pandas as pdCreate a DataFrame with 2 columns having different datatypes −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } )Get the complete information about datatypes −dataFrame.info()ExampleFollowing is the complete code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Roll Number": [ 5, 10, 3, ... Read More

Python - Character repetition string combinations

AmitDiwan
Updated on 21-Sep-2021 07:56:15

160 Views

When it is required to get the character repetitions of a given character, a method is defined that uses the index value to print the repetitions.ExampleBelow is a demonstration of the samedef to_string(my_list): return ''.join(my_list) def lex_recurrence(my_string, my_data, last_val, index_val): length = len(my_string) for i in range(length): my_data[index_val] = my_string[i] if index_val==last_val: print(to_string(my_data)) else: ... Read More

Python - Group contiguous strings in List

AmitDiwan
Updated on 21-Sep-2021 07:52:58

219 Views

When it is required to group the contiguous elements of a string that are present in a list, a method is defined that uses ‘groupby’, and ‘yield’.ExampleBelow is a demonstration of the samefrom itertools import groupby def string_check(elem):    return isinstance(elem, str) def group_string(my_list):       for key, grp in groupby(my_list, key=string_check):          if key: yield list(grp) else: yield from ... Read More

Advertisements