Pandas 报错AttributeError: 'Index' object has no attribute 'remove_unused_levels'

执行代码,将 Series 转换成 DataFrame 时:

s1 = pd.Series(np.random.rand(5),index=['a','s','d','f','g'])
print(s1.unstack())

报错部分情况如下:

  File "D:\python\lib\site-packages\pandas\core\series.py", line 2899, in unstack
    return unstack(self, level, fill_value)
  File "D:\python\lib\site-packages\pandas\core\reshape\reshape.py", line 501, in unstack
    constructor=obj._constructor_expanddim)
  File "D:\python\lib\site-packages\pandas\core\reshape\reshape.py", line 116, in __init__
    self.index = index.remove_unused_levels()
AttributeError: 'Index' object has no attribute 'remove_unused_levels'

原因就是 DataFrame 数据类型有 indexcolumns这两个属性,而上面的 Series 中只有一个索引,所以会报错。需要为Series 添加一列索引,代码如下:

s1 = pd.Series(np.random.rand(5),index=[['a','s','d','f','g'],['one','two','three','four','five']])
print(s1.unstack())

运行结果如下:

       five      four      one     three       two
a       NaN       NaN  0.56761       NaN       NaN
d       NaN       NaN      NaN  0.360103       NaN
f       NaN  0.015191      NaN       NaN       NaN
g  0.786868       NaN      NaN       NaN       NaN
s       NaN       NaN      NaN       NaN  0.978151
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值