How Do I Find Where A Maximum Value Lives in a DataFrame?

Say we’ve created the following dataframe:

df = pd.DataFrame(np.random.randint(0,100, size=(10,4)), columns=list('ABCD'))

Now we want to accomplish two things. We want to loop through all the rows and find which column contains the largest (or smallest) integer for each row, and we want to loop through the columns to find the row containing the largest (or smallest) integer.

Looping through rows to find the column where the largest integer lives:

for idx in df.index:
    print(df.loc[idx].idxmax())

The same thing for the smallest integer:

for idx in df.index:
    print(df.loc[idx].idxmin())

Looping over all the columns to find the row where the largest integer occurs:

for col in df.columns:
    print(df.loc[:, col].idxmax())

The same thing for the smallest integer:

for col in df.columns:
    print(df.loc[:, col].idxmin())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s