Write a program in Python to generate a random array of 30 elements from 1 to 100 and calculate maximum by minimum of each row in a dataframe

PythonPandasServer Side ProgrammingProgramming

Result for generating dataframe maximum by a minimum of each row is

0    43.000000
1    1.911111
2    2.405405
3    20.000000
4    7.727273
5    6.333333

To solve this, we will follow the steps given below −

Solution 1

  • Define a dataframe with size of 30 random elements from 1 to 100 and reshape the array by (6,5) to change 2-D array

df = pd.DataFrame(np.random.randint(1,100,30).reshape(6,5))
  • Create df.apply function inside lambda method to calculate np.max(x)/np.min(x) with axis as 1 and save as max_of_min. It is defined below,

max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
  • Finally print the max_of_min

Example

Let’s check the following code to get a better understanding −

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1,100,30).reshape(6,5))
print("Dataframe is:\n",df)
max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
print("maximum by minimum of each row:\n",max_of_min)

Output

Dataframe is:
   0  1  2  3  4
0  2 13  4 15 86
1 60 53 86 75 45
2 37 85 40 89 88
3 67 33 80  4 74
4 85 71 11 67 81
5 56 85 95 15 94
maximum by minimum of each row:
0    43.000000
1    1.911111
2    2.405405
3    20.000000
4    7.727273
5    6.333333
dtype: float64
raja
Published on 12-Feb-2021 10:45:48
Advertisements