Found 33676 Articles for Programming

Write a program in Python to modify the diagonal of a given DataFrame by 1

Vani Nalliappan
Updated on 24-Feb-2021 09:36:03

385 Views

Assume, you have a dataframe0 1 20 10 20 30 1 40 50 60 2 70 80 90The result for replaced 1 by diagonal of a dataframe is −0 1 2 0 1 20 30 1 40 1 60 2 70 80 1SolutionTo solve this, we will follow the steps given below −Define a dataframeCreate nested for loop to access all rows and columns, for i in range(len(df)):    for j in range(len(df)):Check if the condition to match the diagonals, if it is matched then replace the position by 1. It is defined below, if i == j:    df.iloc[i ... Read More

Write a program in Python to find the lowest value in a given DataFrame and store the lowest value in a new row and column

Vani Nalliappan
Updated on 24-Feb-2021 09:31:05

382 Views

Assume you have a dataframe, one two three 0 12 13 5 1 10 6 4 2 16 18 20 3 11 15 58The result for storing the minimum value in new row and column is −Add new column to store min value  one   two  three min_value 0 12    13   5       5 1 10    6    4       4 2 16    18  20      16 3 11    15  58      11 Add new row to store min value    one   two   three min_value 0   ... Read More

Write a program in Python to read sample data from an SQL Database

Vani Nalliappan
Updated on 24-Feb-2021 09:24:08

570 Views

Assume you have a sqlite3 database with student records and the result for reading all the data is,   Id Name 0 1 stud1 1 2 stud2 2 3 stud3 3 4 stud4 4 5 stud5SolutionTo solve this, we will follow the steps given below −Define a new connection. It is shown below, con = sqlite3.connect("db.sqlite3")Read sql data from the database using below function, pd.read_sql_query()Select all student data from table using read_sql_query with connection, pd.read_sql_query("SELECT * FROM student", con)ExampleLet us see the complete implementation to get a better understanding −import pandas as pd import sqlite3 con = sqlite3.connect("db.sqlite3") df = ... Read More

Write a Pyton program to perform Boolean logical AND, OR, Ex-OR operations for a given series

Vani Nalliappan
Updated on 24-Feb-2021 09:22:02

146 Views

Assume you have a series and the result for Boolean operations, And operation is: 0    True 1    True 2    False dtype: bool Or operation is: 0    True 1    True 2    True dtype: bool Xor operation is: 0    False 1    False 2    True dtype: boolSolutionTo solve this, we will follow the below approach.Define a SeriesCreate a series with boolean and nan valuesPerform boolean True against bitwise & operation to each element in the series defined below, series_and = pd.Series([True, np.nan, False], dtype="bool") & TruePerform boolean True against bitwise | operation ... Read More

Write a program in Python to transpose the index and columns in a given DataFrame

Vani Nalliappan
Updated on 24-Feb-2021 09:19:46

295 Views

Input −Assume you have a DataFrame, and the result for transpose of index and columns are, Transposed DataFrame is   0 1 0 1 4 1 2 5 2 3 6Solution 1Define a DataFrameSet nested list comprehension to iterate each element in the two-dimensional list data and store it in result.result = [[data[i][j] for i in range(len(data))] for j in range(len(data[0]))Convert the result to DataFrame, df2 = pd.DataFrame(result)ExampleLet us see the complete implementation to get a better understanding −import pandas as pd data = [[1, 2, 3], [4, 5, 6]] df = pd.DataFrame(data) print("Original DataFrame is", df) result = [[data[i][j] ... Read More

Write a program in Python to shift the first column and get the value from the user, if the input is divisible by both 3 and 5 and then fill the missing value

Vani Nalliappan
Updated on 24-Feb-2021 10:42:20

85 Views

Input −Assume you have a DataFrame, and the result for shifting the first column and fill the missing values are,  one two three 0 1   10 100 1 2   20 200 2 3   30 300 enter the value 15  one two three 0 15  1   10 1 15  2   20 2 15  3   30SolutionTo solve this, we will follow the below approach.Define a DataFrameShift the first column using below code, data.shift(periods=1, axis=1)Get the value from user and verify if it is divisible by 3 and 5. If the result is true then fill missing ... Read More

Write a program in Python to calculate the default float quantile value for all the element in a Series

Vani Nalliappan
Updated on 24-Feb-2021 09:11:38

116 Views

Input −Assume you have a series and default float quantilevalue is 3.0SolutionTo solve this, we will follow the steps given below −Define a SeriesAssign quantile default value .5 to the series and calculate the result. It is defined below,data.quantile(.5) ExampleLet us see the complete implementation to get a better understanding −import pandas as pd l = [10,20,30,40,50] data = pd.Series(l) print(data.quantile(.5))Output30.0

Write a program in Python to count the records based on the designation in a given DataFrame

Vani Nalliappan
Updated on 24-Feb-2021 09:10:56

143 Views

Input −Assume, we have a DataFrame and group the records based on the designation is −Designation architect    1 programmer   2 scientist    2SolutionTo solve this, we will follow the below approaches.Define a DataFrameApply groupby method for Designation column and calculate the count as defined below,df.groupby(['Designation']).count()ExampleLet us see the following implementation to get a better understanding.import pandas as pd data = { 'Id':[1,2,3,4,5],          'Designation': ['architect','scientist','programmer','scientist','programmer']} df = pd.DataFrame(data) print("DataFrame is",df) print("groupby based on designation:") print(df.groupby(['Designation']).count())OutputDesignation architect    1 programmer   2 scientist    2

Write a program in Python to store the city and state names that start with ‘k’ in a given DataFrame into a new CSV file

Vani Nalliappan
Updated on 24-Feb-2021 09:07:57

679 Views

Input −Assume, we have DataFrame with City and State columns and find the city, state name startswith ‘k’ and store into another CSV file as shown below −City, State Kochi, KeralaSolutionTo solve this, we will follow the steps given below.Define a DataFrameCheck the city starts with ‘k’ as defined below, df[df['City'].str.startswith('K') & df['State'].str.startswith('K')] Finally, store the data in the ‘CSV’ file as below, df1.to_csv(‘test.csv’)ExampleLet us see the following implementation to get a better understanding.import pandas as pd import random as r data = { 'City': ['Chennai', 'Kochi', 'Kolkata'], 'State': ['Tamilnad', 'Kerala', 'WestBengal']} df = pd.DataFrame(data) print("DataFrame is", df) df1 = ... Read More

Write a Python code to select any one random row from a given DataFrame

Vani Nalliappan
Updated on 24-Feb-2021 09:05:45

432 Views

Input −Assume, sample DataFrame is,  Id Name 0 1 Adam 1 2 Michael 2 3 David 3 4 Jack 4 5 PeterOutputput −Random row is   Id    5 Name PeterSolutionTo solve this, we will follow the below approaches.Define a DataFrameCalculate the number of rows using df.shape[0] and assign to rows variable.set random_row value from randrange method as shown below.random_row = r.randrange(rows)Apply random_row inside iloc slicing to generate any random row in a DataFrame. It is defined below, df.iloc[random_row, :]ExampleLet us see the following implementation to get a better understanding.import pandas as pd import random as r data = { ... Read More

Advertisements