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

你可能感兴趣的:(数据分析)