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

Susan Sarandon
Release: 2024-10-17 20:53:30
Original
691 people have browsed it

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)
Copy after login

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)
Copy after login
  1. Assign the result to a new column:
df["C"] = df[["A", "B"]].max(axis=1)
Copy after login

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

A B C
1 -2 1
2 8 8
3 1 3

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

The above is the detailed content of How Can I Calculate the Maximum Value Across Multiple Columns in Pandas?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!