【问题标题】:Pivot Table in PythonPython中的数据透视表
【发布时间】:2018-10-10 11:43:15
【问题描述】:

我对 Python 很陌生,因此我需要您在以下方面的帮助:

我有两个表(数据框):

表 1 包含所有数据,如下所示:

GenDate 列具有生成日期。 日期列有日期。 D 列及以后的值不同

我还有下表:

第一列有“关键字”,可以在表 1 的标题中找到 K 列的日期应在表 1 的 C 列中

我的目标是生成如下表格:

出于说明目的,我省略了几列。

表 1 中的每一列都应该根据写在 Header 上的 Type 进行拆分。

例如。 A_Weeks:Weeks 对应 3 个拆分,Week1、Week2 和 Week3

这些狭缝中的每一个都有一个特定的日期。

在新表中,应该创建 3 列,使用 A_,然后是拆分名称:

A_Week1、A_Week2 和 A_Week3。

对于这些列中的每一列,应使用与每次拆分的日期相对应的值。

我希望解释是好的。

谢谢

【问题讨论】:

  • 查看pd.pivot_table

标签: python python-3.x dataframe pivot-table


【解决方案1】:

您可以使用以下代码获取所需的表(跟随 cmets 并查看 panda api 参考以了解使用的函数):

import numpy as np
import pandas as pd

# initial data
t_1 = pd.DataFrame(
    {'GenDate': [1, 1, 1, 2, 2, 2],
     'Date': [10, 20, 30, 10, 20, 30],
     'A_Days': [11, 12, 13, 14, 15, 16],
     'B_Days': [21, 22, 23, 24, 25, 26],
     'A_Weeks': [110, 120, 130, 140, np.NaN, 160],
     'B_Weeks': [210, 220, 230, 240, np.NaN, 260]})
# initial data
t_2 = pd.DataFrame(
    {'Type': ['Days', 'Days', 'Days', 'Weeks', 'Weeks'],
     'Split': ['Day1', 'Day2', 'Day3', 'Week1', 'Week2'],
     'Date': [10, 20, 30, 10, 30]})

# create multiindex
t_1 = t_1.set_index(['GenDate', 'Date'])
# pivot 'Date' level of MultiIndex - unstack it from index to columns
# and drop columns with all NaN values
tt_1 = t_1.unstack().dropna(axis=1)

# tt_1 is what you need with multi-level column labels

# map to rename columns
t_2 = t_2.set_index(['Type'])
mapping = {
    type_: dict(zip(
        t_2.loc[type_, :].loc[:, 'Date'],
        t_2.loc[type_, :].loc[:, 'Split']))
    for type_ in t_2.index.unique()}

# new column names
new_columns = list()
for letter_type, date in tt_1.columns.values:
    letter, type_ = letter_type.split('_')
    new_columns.append('{}_{}'.format(letter, mapping[type_][date]))

tt_1.columns = new_columns

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2018-09-02
    • 2018-04-06
    相关资源
    最近更新 更多