Fundamentals 5 min read

5 Quick Ways to Add a Row‑wise Max Column in Pandas

This article walks through five concise Pandas techniques for creating a new column that holds the maximum value of two existing columns on each row, complete with code snippets and visual examples to help Python learners master DataFrame operations.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
5 Quick Ways to Add a Row‑wise Max Column in Pandas

Introduction

Hello, I’m a Python enthusiast. A follower in the Python community asked how to compare two columns in a DataFrame and create a new column with the row‑wise maximum value.

Problem Statement

Given a DataFrame with two columns (e.g., cell1 and cell2), we need to generate a new column that contains the larger of the two values for each row.

Solution Methods

Method 1 (by 月神)

Use DataFrame.max across axis 1.

df['max1'] = df[['cell1', 'cell2']].max(axis=1)
df

Method 2 (by 广深‑运营‑n)

Leverage loc with max on the selected columns.

df['max2'] = df.loc[:, ['cell1', 'cell2']].max(axis=1)
df

Method 3 (by 月神)

Apply the built‑in max function row‑wise.

df['max3'] = df[['cell1', 'cell2']].apply(max, axis=1)
df

Method 4 (by 常州‑销售‑MT)

Use assign together with max on the two columns.

df = df.assign(new=df[['cell1', 'cell2']].max(1))

Important detail to avoid errors:

Method 5 (by 上海‑数分‑长城)

Combine NumPy's where with Pandas columns.

df['max4'] = np.where(df['cell1'] > df['cell2'], df['cell1'], df['cell2'])
df

Conclusion

The five approaches above demonstrate straightforward ways to compute a row‑wise maximum between two columns in a Pandas DataFrame, offering both readability and performance options for Python learners.

data-analysiscolumnmax
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.