Pandas 系列中的 align() 方法有何作用?
Pandas 系列的 align 方法用于对齐两个 Pandas 系列对象,使它们基于相同的行和/或列配置,这可以通过指定 join、axis 等参数来实现。
Pandas 系列的 align 方法并非将两个系列对象合并,而是按特定顺序对齐它们。此方法接受 10 个参数,分别为 "other、join='outer'、axis=None、level=None、copy=True、fill_value=None、method=None、limit=None、fill_axis=0、broadcast_axis=None"。 在这些参数中,other、join 和 axis 参数非常重要。输出序列对象的对齐取决于这些参数。
示例 1
import pandas as pd
s1 = pd.Series([8,4,2,1], index=[5,3,4,2])
s2 = pd.Series([15,12,10,11],index=[1,2,4,5])
print(s1)
print(s2)
a,b = s1.align(s2)
print("对齐方法的输出")
print(a)
print(b)
解释
s1 和 s2 是两个 Pandas 序列对象,索引标签分别为 [1,2,4,5] 和 [2,3,4,5]。我们对这两个系列对象应用了不带任何参数的 align 方法,并得到了另外两个系列对象作为此 align 方法的输出。
输出
5 8 3 4 4 2 2 1 dtype: int64 1 15 2 12 4 10 5 11 dtype: int64 不带任何参数的 align 方法的输出。 1 NaN 2 1.0 3 4.0 4 2.0 5 8.0 dtype: float64 1 15.0 2 12.0 3 NaN 4 10.0 5 11.0 dtype: float64
以上 4 个系列对象分别为 s1、s2、a 和 b。顶部两个对象为 s1 和 s2,底部两个对象由 pandas 系列的 align 方法使用默认参数生成。
s1 中的索引标签已重新排列,以便与 s2 中的索引对齐。
已将标记为"1"的索引添加到 s1,并将标记为"3"的索引添加到 s2。这些值已用 NaN 填充。这是因为默认的 join 参数是索引标签上的外连接。
示例 2
import pandas as pd
s1 = pd.Series([8,4,2,1], index=[5,3,4,2])
s2 = pd.Series([15,12,10,11],index=[1,2,4,5])
print(s1)
print(s2)
a,b = s1.align(s2, join='right')
print("带有 join 参数的 align 方法的输出。")
print(a)
print(b)
解释
现在,我们将带有 ‘right’ 选项的 join 参数应用于上述相同示例。并观察下面输出块中的差异。
输出
5 8 3 4 4 2 2 1 dtype: int64 1 15 2 12 4 10 5 11 dtype: int64 带有连接参数的对齐方法的输出。 1 NaN 2 1.0 4 2.0 5 8.0 dtype: float64 1 15 2 12 4 10 5 11 dtype: int64
仅保留"右侧"系列对象 (s2) 中找到的行。索引标签"3"不再存在。这是因为我们对系列对象进行了右连接。

