Skip to content
How to Compute Row-wise Means in Pandas with One-Liner Code
Fundamentals 3 min read

How to Compute Row-wise Means in Pandas with One-Liner Code

This article demonstrates two concise methods to add a column of average marks to a Pandas DataFrame by using lambda with np.mean or directly applying NumPy's mean function, complete with sample data, expected output, and step‑by‑step code snippets.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining

Introduction

Hello, I'm PiPi. Recently a question about processing data with Pandas was asked in a Python community. The original data is shown below.

df = pd.DataFrame({
    'student_id': ['S001','S002','S003'],
    'marks': [[88,89,90],[78,81,60],[84,83,91]]
})
df

The expected output is a DataFrame with an additional column containing the mean of each marks list.

Implementation

Method 1

The following code uses a lambda function with np.mean to compute the row‑wise mean.

df['dmean'] = df['marks'].map(lambda x: np.mean(x))

Method 2

An optimized version applies NumPy's mean directly via map or apply.

df['dmean'] = df['marks'].map(np.mean)
# or
df['dmean'] = df['marks'].apply(np.mean)

Conclusion

This article presented two concise solutions for adding a column of average marks to a Pandas DataFrame, helping readers solve the original problem efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythondataframePandasNumPydata-analysis
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.