"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Calculate the Maximum Value Across Multiple Columns in Pandas?

How Can I Calculate the Maximum Value Across Multiple Columns in Pandas?

Published on 2024-11-07
Browse:293

How Can I Calculate the Maximum Value Across Multiple Columns in Pandas?

Find the Maximum Value Across Multiple Columns in Pandas

Suppose you have a dataframe with several columns and wish to create a new column containing the maximum value from two or more existing columns. For instance, given columns A and B, you need to create a column C where:

C = max(A, B)

To accomplish this task:

  1. Use the max function along with axis=1 to calculate the maximum value for each row across the specified columns:
df[["A", "B"]].max(axis=1)
  1. Assign the result to a new column:
df["C"] = df[["A", "B"]].max(axis=1)

This generates a new column C containing the maximum value for each row between columns A and B:

ABC
1-21
288
313

Note that this technique can be generalized to find the maximum value across any number of columns.

Release Statement This article is reprinted at: 1729169537 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3