Found 33676 Articles for Programming

Python Program to Remove Palindromic Elements from a List

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

355 Views

When it is required to remove palindromic elements from a list, list comprehension and the ‘not’ operator are used.ExampleBelow is a demonstration of the samemy_list = [56, 78, 12, 32, 4, 8, 9, 100, 11] print("The list is : ") print(my_list) my_result = [elem for elem in my_list if int(str(elem)[::-1]) not in my_list] print("The result is : " ) print(my_result)OutputThe list is : [56, 78, 12, 32, 4, 8, 9, 100, 11] The result is : [56, 78, 12, 32, 100]ExplanationA list is defined and displayed on the console.A list comprehension is used to iterate over the ... Read More

Python Pandas - Count the number of rows in each group

AmitDiwan
Updated on 20-Sep-2021 08:05:51

361 Views

Use the group.size() to count the number of rows in each group. Import the required library −import pandas as pdCreate a DataFrame −dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'], 'Quantity': [10, 50, 10, 20, 25, 50], 'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'] })Group by columns −dataFrame.groupby(["Product Category", "Quantity"]) Now, count the group size to get the count of rows in each group.ExampleFollowing is the complete code −import pandas as pd # create a dataframe dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'], 'Quantity': [10, 50, 10, 20, ... Read More

Python – N sized substrings with K distinct characters

AmitDiwan
Updated on 20-Sep-2021 08:08:31

260 Views

When it is required to split ‘N’ sized substrings with ‘K’ distinct characters, it is iterated over, and the ‘set’ method is used to get the different combinations.ExampleBelow is a demonstration of the samemy_string = 'Pythonisfun' print("The string is : ") print(my_string) my_substring = 2 my_chars = 2 my_result = [] for idx in range(0, len(my_string) - my_substring + 1): if (len(set(my_string[idx: idx + my_substring])) == my_chars): my_result.append(my_string[idx: idx + my_substring]) print("The resultant string is : ") print(my_result)OutputThe string is : Pythonisfun The resultant string is : ['Py', 'yt', ... Read More

Python – Merge Dictionaries List with duplicate Keys

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

765 Views

When it is required to merge dictionaries list with duplicate keys, the keys of the strings are iterated over and depending on the condition, the result is determined.ExampleBelow is a demonstration of the samemy_list_1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}] my_list_2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}] print("The first list is : ") print(my_list_1) print("The second list is : ") print(my_list_2) for i in range(0, len(my_list_1)):    id_keys = list(my_list_1[i].keys())    for key in my_list_2[i]:       if key not in id_keys: ... Read More

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

AmitDiwan
Updated on 20-Sep-2021 07:58:37

718 Views

To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −ascending=FalseImport 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 descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)ExampleFollowing is ... Read More

Python - Move a column to the first position in Pandas DataFrame?

AmitDiwan
Updated on 20-Sep-2021 07:48:45

1K+ Views

Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'], "Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) Move column "Roll Number" to 1st position by first popping the column out −shiftPos = dataFrame.pop("Roll Number")Insert column on the 1st position −dataFrame.insert(0, "Roll Number", shiftPos) ExampleFollowing is the code −import pandas as pd # ... Read More

Python – Display only non-duplicate values from a DataFrame

AmitDiwan
Updated on 20-Sep-2021 07:42:04

4K+ Views

We will see how to display only non-duplicated values. At first, we will create a DataFrame with duplicate values −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', 'Kat', 'Ted'], "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'] } )Above, we have created 2 columns. To display only non-duplicated values, use the duplicated() method and logical NOT. Through this, non-duplicated values will be fetched −dataFrame[~dataFrame.duplicated('Student')] ExampleFollowing is the complete code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Robin', 'Scarlett', ... Read More

Python – Reshape the data in a Pandas DataFrame

AmitDiwan
Updated on 20-Sep-2021 07:34:11

779 Views

We can easily reshape the data by categorizing a specific column. Here, we will categorize the “Result”column i.e. Pass and Fail values in numbers form.Import the required library −import pandas as pdCreate a DataFrame with 2 columns −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'], "Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } )Reshape the data using the map() function and just set ‘Pass’ to 1 and ‘Fail’ to 0 −dataFrame['Result'] = dataFrame['Result'].map({'Pass': 1, 'Fail': 0, }) ExampleFollowing is the code − import pandas as pd # Create DataFrame dataFrame ... Read More

Python - Convert Pandas DataFrame to binary data

AmitDiwan
Updated on 20-Sep-2021 07:27:52

4K+ Views

Use the get_dummies() method to convert categorical DataFrame to binary data. Following is our Pandas DataFrame with 2 columns −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Scarlett', 'Kat'], "Result": ['Pass', 'Fail', 'Fail', 'Pass', 'Pass'] } )Use the get_dummies() and set the column which you want to convert to binary form. Here, we want the Result in “Pass” and “Fail” form to be visible. Therefore, we will set the “Result” column −pd.get_dummies(dataFrame["Result"]ExampleFollowing is the code −import pandas as pd # Create DataFrame dataFrame = pd.DataFrame(    {       "Student": ['Jack', ... Read More

Renaming column names – Python Pandas

AmitDiwan
Updated on 20-Sep-2021 07:21:18

285 Views

We can use the rename() method to rename column names. Let’s say the following is our Pandas DataFrame with 3 columns −dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'], "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], "Units": [90, 120, 100, 150, 200, 130] } )We will rename two columns i.e. “Car” to “Car Names” and “Reg_Price” to “Registration Cost”:dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'}) ExampleFollowing is the code − import pandas as pd # Create DataFrame dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', ... Read More

Advertisements