首页 > 解决方案 > 熊猫系列重命名轴失败

问题描述

我正在从字典创建 Pandas MulitiIndex 系列。它正常成功,但当 dict 为空时 rename_axis 失败

series = pd.Series({('a','b','c'):1,('a','d','e'):2}, dtype='float64').rename_axis(['first_column','second_column','third_column'])

series

first_column  second_column  third_column
a             b              c               1.0
              d              e               2.0
dtype: float64

字典为空时失败

series = pd.Series({}, dtype='float64').rename_axis(['first_column','second_column','third_column'])

   1237             raise ValueError("Names must be a list-like")
   1238         if len(values) != 1:
-> 1239             raise ValueError(f"Length of new names must be 1, got {len(values)}")
   1240 
   1241         # GH 20527

ValueError: Length of new names must be 1, got 3

我可以检查字典是否为空并以不同的方式创建系列

series = pd.Series({}, dtype='float64', index=pd.MultiIndex.from_tuples([], names=['first_column', 'second_column', 'third_column']))

想知道是否有更好的方法来创建系列,避免空字典的显式 if 条件。

谢谢

标签: pythonpandas

解决方案


推荐阅读