如何对齐多个熊猫系列或数据框

时间:2018-09-25 18:11:25

标签: python pandas

是否可以对齐多个熊猫系列或数据框。

说我有一个熊猫系列的清单,想:

  • 仅保留所有系列中存在的索引元素(内部 加入)
  • 所有系列的索引元素均为所有索引的并集 (外部加入)

以下代码实现了我想要的(内部和外部联接)

import pandas as pd
import itertools

def align(pd_objects, join='outer', axis=0):
    """apply align on all combinations of the list of pd objects"""
    for (i, j) in itertools.combinations(range(len(pd_objects)), 2):
        (pd_objects[i], pd_objects[j]) = pd_objects[i].align(pd_objects[j], join, axis)
    return tuple(pd_objects)

s_1 = pd.Series(['a', 'b', 'c', 'd'], index=[1, 2, 3, 4])
s_2 = pd.Series(['b', 'c', 'd'], index=[2, 3, 4])
s_3 = pd.Series(['a', 'b', 'c'], index=[1, 2, 3])

位置:

(s_1x, s_2x, s_3x) = align([s_1, s_2, s_3], join='inner', axis=0)

返回索引为['b','c']的三个系列

并且:

(s_1y, s_2y, s_3y) = align([s_1, s_2, s_3], join='outer', axis=0)

返回索引为['a','b','c','d']的三个系列

但是我想还有一种更Python化且更有效的方法

0 个答案:

没有答案