Fundamentals 4 min read

How to Transform Complex Excel Data with Pandas: A Step‑by‑Step Guide

This article walks through a real‑world Pandas problem posted in a Python community, showing how to read multiple Excel sheets, reshape the data, rename columns, and filter the result to match a desired table layout, complete with code and screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Transform Complex Excel Data with Pandas: A Step‑by‑Step Guide

1. Introduction

During the National Day holiday, a member of the Python Silver Group asked a question about handling data with Pandas. The goal was to transform an Excel file into a specific table format shown in the target screenshot.

2. Implementation

The initial solution used pd.concat to read all sheets, unstack the level, and rename columns with a lambda expression. The code was:

import pandas as pd

df = pd.concat(pd.read_excel(r"LT211120Y6_output(1).xlsx", sheet_name=None)).unstack(level=0)
df.columns = df.columns.map(lambda x: '{1}.{0}'.format(x[1].strip('day'), x[0]))
print(df)

The resulting table was close to the expected layout, as shown in the screenshot.

A refined version added conditional column handling and selected only the relevant columns:

import pandas as pd

df = pd.concat(pd.read_excel(r"LT211120Y6_output(1).xlsx", sheet_name=None)).unstack(level=0)
df.columns = df.columns.map(lambda x: '{1}{0}'.format(x[1].strip('day'), x[0]) if x[0] == '血糖时间' else x[0])
df = df[['血糖时间2', '血糖值']].rename(columns={'血糖时间2': '血糖时间'})
print(df)

The final output matched the desired table, successfully solving the fan's problem.

3. Conclusion

The article demonstrated a practical Pandas workflow for reshaping multi‑sheet Excel data, providing clear code snippets and visual results. It helped the community member achieve the required data format and illustrated how to adjust column names and filter rows effectively.

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.

data-processingExcelpandasCode Tutorial
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.