Skip to main content
 首页 » 编程设计

python之df.reindex() 和 df.loc[] 的区别

2025年05月04日15yxwkf

假设我想计算 relative complement两个 MultiIndex 数据帧之间的 df2 - df1。根据我在 this answer 中看到的内容,假设它们具有相同的索引模式来自 Andy Hayden,我可以执行以下操作:

diff_indices = df2.index - df1.index 

然后:

  1. df2.reindex(diff_indices, inplace=True)

    或

  2. df2 = df2.loc[diff_indices]

上面的 1. 和 2. 有什么区别? df.reindex 和 df.loc 有什么区别?

请您参考如下方法:

这两种方法都返回一个新的系列/数据框,并且基本上做同样的事情。

看似冗余的原因是,虽然使用 loc 在语法上有限制(您只能将单个参数传递给 __getitem__),reindex 是一种方法,它支持接受各种可选参数。 ( docs )