Found 26504 Articles for Server Side Programming

Python – Random insertion of elements K times

AmitDiwan
Updated on 13-Sep-2021 10:43:09

300 Views

When it is required to randomly insert elements K times, the ‘random’ package and methods from the random package along with a simple iteration is used.ExampleBelow is a demonstration of the same −import random my_list = [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) to_add_list = ["Python", "Object", "oriented", "language", 'cool'] K = 3 print("The value of K is ") print(K) for element in range(K): index = random.randint(0, len(my_list)) ... Read More

Python program to find all the Combinations in a list with the given condition

AmitDiwan
Updated on 13-Sep-2021 10:40:48

574 Views

When it is required to find all the combinations in a list with a specific condition, a simple iteration, the ‘isinstance’ method, the ‘append’ method and indexing are used.ExampleBelow is a demonstration of the same −print("Method definition begins") def merge_the_vals(my_list_1, my_list_2, K): index_1 = 0 index_2 = 0 while(index_1 < len(my_list_1)): for i in range(K): yield my_list_1[index_1] index_1 += 1 ... Read More

Python Pandas - Query the columns of a DataFrame

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

414 Views

To query the columns of a Pandas DataFrame, use the query(). We are querying to filter records. At first, let us create a Pandas DataFramedataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Using query() to query columns with conditions −print(dataFrame.query('Opening_Stock >=500 & Closing_Stock < 1000 & Product.str.startswith("P").values'))ExampleFollowing is the complete code −import pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "PenDrive", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...", dataFrame # using query() to query columns print"Querying columns to filter records..." print(dataFrame.query('Opening_Stock >=500 & Closing_Stock ... Read More

Python Pandas - How to select multiple rows from a DataFrame

AmitDiwan
Updated on 14-Sep-2021 15:14:34

3K+ Views

To select multiple rows from a DataFrame, set the range using the : operator. At first, import the require pandas library with alias −import pandas as pdNow, create a new Pandas DataFrame −dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]], index=['w', 'x', 'y', 'z'], columns=['a', 'b'])Select multiple rows using the : operator −dataFrame[0:2]ExampleFollowing is the 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 # select rows with loc print"Select rows by passing label..." print(dataFrame.loc['z']) ... Read More

Python - How to select a column from a Pandas DataFrame

AmitDiwan
Updated on 14-Sep-2021 15:12:08

1K+ Views

To select a column from a DataFrame, just fetch it using square brackets. Mention the column to select in the brackets and that’s it, for exampledataFrame[‘ColumnName’]At first, import the required library −import pandas as pdNow, create a DataFrame. We have two columns in it −dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )To select only a single column, mention the column name using the square bracket as shown below. Here, our ... Read More

Python - Merge Pandas DataFrame with Outer Join

AmitDiwan
Updated on 14-Sep-2021 15:09:01

2K+ Views

To merge Pandas DataFrame, use the merge() function. The outer join is implemented on both the DataFrames by setting under the “how” parameter of the merge() function i.e. −how = “outer”At first, let us import the pandas library with an alias −import pandas as pdLet us create DataFrame1 −dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )Let us now create DataFrame2 −dataFrame2 = pd.DataFrame( { ... Read More

Merge Python Pandas dataframe with a common column and set NaN for unmatched values

AmitDiwan
Updated on 14-Sep-2021 15:04:06

6K+ Views

To merge two Pandas DataFrame with common column, use the merge() function and set the ON parameter as the column name. To set NaN for unmatched values, use the “how” parameter and set it left or right. That would mean, merging left or right.At first, let us import the pandas library with an alias −import pandas as pdLet us create DataFrame1 −dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )Let us ... Read More

Python – Drop multiple levels from a multi-level column index in Pandas dataframe

AmitDiwan
Updated on 13-Sep-2021 09:15:08

6K+ Views

To drop multiple levels from a multi-level column index, use the columns.droplevel() repeatedly. We have used the Multiindex.from_tuples() is used to create indexes column-wise.At first, create indexes column-wise −items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"), ("Col 2", "Col 2", "Col 2"), ("Col 3", "Col 3", "Col 3")])Next, create a multiindex array and form a multiindex dataframe −arr = [np.array(['car', 'car', 'car', 'bike', 'bike', 'bike', 'truck', 'truck', 'truck']), np.array(['valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC'])] # forming multiindex dataframe dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr, columns=items)Label the index −dataFrame.index.names = ['level 0', 'level 1'] Drop a level ... Read More

Python – Drop a level from a multi-level column index in Pandas dataframe

AmitDiwan
Updated on 13-Sep-2021 11:44:16

3K+ Views

To drop a level from a multi-level column index, use the columns.droplevel(). We have used the Multiindex.from_tuples() is used to create indexes column-wise.At first, create indexes column-wise −items = pd.MultiIndex.from_tuples([("Col 1", "Col 1", "Col 1"), ("Col 2", "Col 2", "Col 2"), ("Col 3", "Col 3", "Col 3")])Next, create a multiindex array and form a multiindex dataframearr = [np.array(['car', 'car', 'car', 'bike', 'bike', 'bike', 'truck', 'truck', 'truck']),    np.array(['valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC', 'valueA', 'valueB', 'valueC'])] # forming multiindex dataframe dataFrame = pd.DataFrame(np.random.randn(9, 3), index=arr, columns=items)Label the index −dataFrame.index.names = ['level 0', 'level 1']Drop a level at index ... Read More

Python – Ascending Order Sort grouped Pandas dataframe by group size?

AmitDiwan
Updated on 14-Sep-2021 14:33:09

525 Views

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending order, use sort_values(). The size() method is used to get the dataframe size.For ascending order sort, use the following in sort_values() −ascending=TrueAt first, create a pandas dataframe −dataFrame = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'], "Reg_Price": [1000, 1400, 1000, 900, 1700, 900] } )Next, group according to Reg_Price column and sort in ascending order −dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)ExampleFollowing is the code −import pandas as pd # dataframe ... Read More

Advertisements