【问题标题】:How to create fact table using python in ETL project如何在 ETL 项目中使用 python 创建事实表
【发布时间】:2021-10-01 02:11:50
【问题描述】:

我必须使用 python 在一个新项目中创建一个事实表。谁能帮我创建以下结构。第一个表是我的输入事务表 -

Order ID Order Date Region Sales Profit Quantity
CA-2013-152156 09-11-2014 00:00:00 East 261.96 41.9136 9
CA-2013-138688 2014-06-13 00:00:00 West 14.62 6.8714 2
US-2012-108966 2013-10-11 00:00:00 South 957.5775 -383.031 5
CA-2011-115812 2012-06-09 00:00:00 West 48.86 14.1694 7

输出将类似于下表。基本上我需要创建一个包含两个新列的事实表 -1) Measure 和 2)Values 。 Sales、Profit 和 Quantity 列需要与其他属性列一起在第二个表中转置。

Order ID Order Date Region Measure Value
CA-2013-152156 2014-11-09 00:00:00 South Sales 261.96
CA-2013-152156 2014-11-09 00:00:00 South Profit 41.9136
CA-2013-152156 2014-11-09 00:00:00 South Quantity 2
CA-2013-138688 2014-06-13 00:00:00 West Sales 14.62
CA-2013-138688 2014-06-13 00:00:00 West Profit 6.8714
CA-2013-138688 2014-06-13 00:00:00 West Quantity 2
US-2012-108966 2013-10-11 00:00:00 South Sales 957.5775
US-2012-108966 2013-10-11 00:00:00 South Profit -383.031
US-2012-108966 2013-10-11 00:00:00 South Quantity 5

出于示例目的,我使用了来自示例超市数据的一个小数据框

【问题讨论】:

  • 您能否编辑您的问题并将数据框转换为文本形式?所以我们可以复制粘贴吗?
  • 我不明白所需的输出。你必须解释它。
  • 预期的输出看起来像是在sales,profit 上使用groupby([id, date, region])sum() 创建的,然后使用pivot
  • 我已经编辑了表格。任何人都可以指导我。 Group by 选项无法正常工作。

标签: python pandas dataframe schema etl


【解决方案1】:
  • 您的样本数据与您想要的输出不匹配 ....
  • 这是groupby()Value之外的所有列的简单案例
  • 然后unstack("measure")
import io
import pandas as pd


df = pd.DataFrame({'Order ID': ['CA-2013-152156',
  'CA-2013-152156',
  'CA-2013-152156',
  'CA-2013-138688',
  'CA-2013-138688',
  'CA-2013-138688',
  'US-2012-108966',
  'US-2012-108966',
  'US-2012-108966'],
 'Order Date': ['2014-11-09 00:00:00',
  '2014-11-09 00:00:00',
  '2014-11-09 00:00:00',
  '2014-06-13 00:00:00',
  '2014-06-13 00:00:00',
  '2014-06-13 00:00:00',
  '2013-10-11 00:00:00',
  '2013-10-11 00:00:00',
  '2013-10-11 00:00:00'],
 'Region': ['South',
  'South',
  'South',
  'West',
  'West',
  'West',
  'South',
  'South',
  'South'],
 'Measure': ['Sales',
  'Profit',
  'Quantity',
  'Sales',
  'Profit',
  'Quantity',
  'Sales',
  'Profit',
  'Quantity'],
 'Value': [261.96, 41.9136, 2.0, 14.62, 6.8714, 2.0, 957.5775, -383.031, 5.0]})

df.groupby([c for c in df.columns if c!="Value"]).sum().unstack("Measure").droplevel(0,1).reset_index()


Order ID Order Date Region Profit Quantity Sales
0 CA-2013-138688 2014-06-13 00:00:00 West 6.8714 2 14.62
1 CA-2013-152156 2014-11-09 00:00:00 South 41.9136 2 261.96
2 US-2012-108966 2013-10-11 00:00:00 South -383.031 5 957.577

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多