python - swaplevel() 和 reorder_levels() 有什么区别?

标签 python pandas indexing

在 pandas 中使用分层索引级别时,swaplevel() 之间有什么区别?和 reorder_levels()

最佳答案

当只有两个级别时swaplevelreorder_levels几乎相同,但是当你的df有超过3个级别时,个人认为reorder_levels更优雅的方式

例如:

idx = pd.MultiIndex.from_arrays([[1, 1, 2], [1, 2, 2], [3, 3, 3],[1,1,1]])
df = pd.DataFrame(columns=idx, index=[1, 2, 3, 4])

如果我们想将订单级别=[0,1,2,3]更改为[3,2,1,0]

使用swaplevel:需要多次调用

df.swaplevel(0,3,axis=1).swaplevel(1,2,axis=1)
     1          
     3          
     1    2     
     1    1    2
1  NaN  NaN  NaN
2  NaN  NaN  NaN
3  NaN  NaN  NaN
4  NaN  NaN  NaN

使用reorder_levels:仅一次调用

df.reorder_levels([3,2,1,0],axis=1)
     1          
     3          
     1    2     
     1    1    2
1  NaN  NaN  NaN
2  NaN  NaN  NaN
3  NaN  NaN  NaN
4  NaN  NaN  NaN

关于python - swaplevel() 和 reorder_levels() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191730/

相关文章:

python - Pandas read_csv : Ignore second header line

python - 在 Python 中使用 Scipy 进行约束样条拟合

string - 如何在 Rust 中找到字符串中字符的索引?

python - 为 python 错误导入键盘

Python制表,将元素附加到当前表

python - 按天重新采样并对具有日期时间开始和日期时间结束的 DataFrame 进行分类

java if语句没有破坏 "for loop"

indexing - CQL SELECT 大于对索引非键列的查询

python - 将 SRV DNS 记录与 python requests 库结合使用

python - 如何在 Tensorflow 中实现提前停止并降低平台学习率?