【问题标题】:Extract series objects from Pandas DataFrame从 Pandas DataFrame 中提取系列对象
【发布时间】:2016-09-29 16:44:51
【问题描述】:

我有一个包含列的数据框

['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory']

对于每个“零件编号”,每个零件编号上的“日历年/月”都是唯一的。

我想将每个零件编号转换为以“日历年/月”为索引、“销售”或“库存”为值的单变量系列。

如何使用 pandas 内置函数而不是手动迭代数据框来完成此操作?

【问题讨论】:

  • 如果“日历年/月”是唯一的,您可以将其设置为数据框的索引。这不能解决你的问题吗?
  • df = pandas.DataFrame(file, index=['Calendar Year/Month'], columns = ['Sales', 'Inventory'])
  • 我说错了。每个零件编号中的“日历年/月”是唯一的。但是,我认为这可能仍然有效。

标签: python pandas dataframe time-series


【解决方案1】:

在 pandas 中,这称为 MultiIndex。试试:

import pandas as pd
df = pd.DataFrame(file, 
        index=['Part Number', 'Calendar Year/Month'], 
        columns = ['Sales', 'Inventory'])

【讨论】:

    【解决方案2】:

    您可以使用 groupby 方法,例如:

    grouped_df = df.groupby('Part Number')
    

    然后您可以访问某个零件号的df并轻松设置索引,例如:

    new_df = grouped_df.get_group('THEPARTNUMBERYOUWANT').set_index('Calendar Year/Month')
    

    如果你只想要两列,你可以这样做:

    print new_df[['Sales', 'Inventory']]]
    

    【讨论】:

      【解决方案3】:

      从这里的答案和 cmets,以及更多的研究,我以以下解决方案结束。

      temp_series = df[df[ "Part Number" == sku ] ].pivot(columns = ["Calendar Year/Month"], values = "Sales").iloc[0]
      

      其中 sku 是来自 df["Part Number"].unique() 的特定部件号

      这将为您提供由“日历年/月”索引的单变量时间序列(temp_series),其值为“销售”EG:

      1.2015     NaN
      1.2016     NaN
      2.2015     NaN
      2.2016     NaN
      3.2015     NaN
      3.2016     NaN
      4.2015     NaN
      4.2016     NaN
      5.2015     NaN
      5.2016     NaN
      6.2015     NaN
      6.2016     NaN
      7.2015     NaN
      7.2016     NaN
      8.2015     NaN
      8.2016     NaN
      9.2015     NaN
      10.2015    NaN
      11.2015    NaN
      12.2015    NaN
      Name: 161, dtype: float64
      
      <class 'pandas.core.series.Series'>])
      

      从列

      ['CPL4', 'Part Number', 'Calendar Year/Month', 'Sales', 'Inventory']
      

      【讨论】:

        猜你喜欢
        • 2019-12-27
        • 2023-01-17
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-03
        相关资源
        最近更新 更多