[英]pivot_table() to a df no numeric types to aggregate
我有一个 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
我猜这是因为ep-ratio
None
值,我不能在None
使用NaN
,因为它造成了其他问题。
那么我怎样才能对这个数据帧进行非规范化呢?
预期结果:
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 没有数字类型来聚合它没有帮助
你接近,需要parameter
列添加到列表中,选择列value
前unstack
和最后使用reset_index
与rename_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.