返回介绍

solution / 2800-2899 / 2890.Reshape Data Melt / README_EN

发布于 2024-06-17 01:02:59 字数 2119 浏览 0 评论 0 收藏 0

2890. Reshape Data Melt

中文文档

Description

DataFrame report
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| product   | object |
| quarter_1   | int  |
| quarter_2   | int  |
| quarter_3   | int  |
| quarter_4   | int  |
+-------------+--------+

Write a solution to reshape the data so that each row represents sales data for a product in a specific quarter.

The result format is in the following example.

 

Example 1:

Input:
+-------------+-----------+-----------+-----------+-----------+
| product   | quarter_1 | quarter_2 | quarter_3 | quarter_4 |
+-------------+-----------+-----------+-----------+-----------+
| Umbrella  | 417     | 224     | 379     | 611     |
| SleepingBag | 800     | 936     | 93    | 875     |
+-------------+-----------+-----------+-----------+-----------+
Output:
+-------------+-----------+-------+
| product   | quarter   | sales |
+-------------+-----------+-------+
| Umbrella  | quarter_1 | 417   |
| SleepingBag | quarter_1 | 800   |
| Umbrella  | quarter_2 | 224   |
| SleepingBag | quarter_2 | 936   |
| Umbrella  | quarter_3 | 379   |
| SleepingBag | quarter_3 | 93  |
| Umbrella  | quarter_4 | 611   |
| SleepingBag | quarter_4 | 875   |
+-------------+-----------+-------+
Explanation:
The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter.

Solutions

Solution 1

import pandas as pd


def meltTable(report: pd.DataFrame) -> pd.DataFrame:
  return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文