【问题标题】:pivot_table() to a df no numeric types to aggregatepivot_table() 到 df 没有要聚合的数字类型
【发布时间】:2019-03-03 00:28:53
【问题描述】:

我有一个 df,我正在尝试对其进行非规范化。基本上我想将参数值(例如'inst-cap-c''cap-lo-c' 等)更改为列。

为了做到这一点,到目前为止,pandas 库中有 2 种方法。与他们两个我都遇到了一些问题并且无法对这个df进行非规范化......

df 如下所示(为简单起见...):

data       
   Site  Storage Commodity     parameter    value
0  Mid   Pump    Elec         inst-cap-c        0
1  Mid   Pump    Elec           cap-lo-c        0
2  Mid   Pump    Elec           cap-up-c  1.5e+15
3  Mid   Pump    Elec         inst-cap-p        0
4  Mid   Pump    Elec           cap-lo-p        0
...
52 South Pump    Elec               wacc     0.07
53 South Pump    Elec       depreciation       50
54 South Pump    Elec               init        1
55 South Pump    Elec          discharge  3.5e-06
56 South Pump    Elec           ep-ratio     None

当我尝试通过以下方式创建具有参数值的列时:

data.pivot_table(values='value',
                 index=['Site', 'Storage', 'Commodity'],
                 columns='parameter')

它只是说:*** pandas.core.base.DataError: No numeric types to aggregate

我猜这是因为None 的值是ep-ratio,我不能使用NaN 而不是None,因为它会产生其他问题。

那么我该如何去规范化这个数据框呢?

预期结果:

data       
   Site    Storage  Commodity  inst-cap-c  cap-lo-c cap-up-c ... ep-ratio
0  Mid     Pump     Elec                0         0  1.5e+15 ...     None
1  North   Pump     Elec                0         0  1.5e+15 ...     None
2  South   Pump     Elec                0         0  1.5e+15 ...     None

额外:

data.set_index(['Site', 'Storage','Commodity'], append=True).unstack('parameter')
*** KeyError: 'Level parameter not found'

我也检查了这个:pivot_table No numeric types to aggregate 它没有帮助

【问题讨论】:

  • “我不能使用 NaN 而不是 None,因为它会产生其他问题。”您应该更喜欢使用 NaN,您也许可以在 pivot 之后将 NaN 替换为 None 但是您应该更喜欢简单地使用 NaN。
  • @AndyHayden with NaN 存在 pivot_table() 的问题:因此它允许您选择是否要通过 dropna=True 删除值,它是默认设置的。问题是我必须删除一些数据,其中一些像上面的数据我不应该删除它......这是因为我的数据结构。所以我不能最终得到一个一致的方法,我可以使用我的模型数据的每一个案例。这就是为什么我之前将 NaN 值更改为 None 的原因。现在我无法执行非规范化...寻找更好的建议...

标签: python pandas dataframe pivot-table


【解决方案1】:

你很接近,需要将parameter列添加到列表中,在unstack之前选择列value,最后使用reset_indexrename_axis进行数据清理:

df = (data.set_index(['Site', 'Storage','Commodity','parameter'])['value']
          .unstack()
          .reset_index()
          .rename_axis(None, axis=1))
print (df)
    Site Storage Commodity cap-lo-c cap-lo-p cap-up-c depreciation discharge  \
0    Mid    Pump      Elec        0        0  1.5e+15          NaN       NaN   
1  South    Pump      Elec      NaN      NaN      NaN           50   3.5e-06   

  ep-ratio init inst-cap-c inst-cap-p  wacc  
0      NaN  NaN          0          0   NaN  
1     None    1        NaN        NaN  0.07  

【讨论】:

    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2021-09-22
    • 2020-04-02
    • 2019-06-23
    • 1970-01-01
    • 2012-10-02
    相关资源
    最近更新 更多