python - 熊猫系列重命名轴失败
问题描述
我正在从字典创建 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 条件。
谢谢
解决方案
推荐阅读
- html - 网页宽于所有屏幕,包括桌面
- c++ - 如何防止被shared_ptr破坏的捕获的“this”的悬空指针?
- junit - 是否可以在不使用 powermock 的情况下在 Mockito 中模拟 UUID?
- javascript - 函数中的相同函数,保留变量/元素
- html - SVG在其高度由字体设置的父div中居中
- ssas - DAX - 非活跃客户
- annotations - org.testng.TestNGException:以下方法在通过TestNG执行测试时有循环依赖
- social-tables - 如何在没有每次授权的情况下使用 Social Tables API
- java - Java 帮助 - MySQL - SQLConnector“无限递归”和控制台打印是无限的
- javascript - 具有本机反应但错误的新项目