Pandas split-apply-combine,为什么结合pd.concat([df])在排序时有效?

时间:2018-04-30 18:52:46

标签: python pandas merge pandas-groupby pandas-apply

我使用pandas进行split-apply-merge类型的工作流程。 'apply'部分返回DataFrame。首次对运行gropupby的DataFrame进行排序时,只需从DataFrame返回apply即可ValueError: cannot reindex from a duplicate axis。相反,当我返回pd.concat([df])(而不仅仅是return df)时,我发现它可以正常工作。如果我不对DataFrame进行排序,则两种合并结果的方式都能正常工作。我希望排序必须对索引做一些事情,但我不明白是什么。有人可以解释一下吗?

import pandas as pd
import numpy as np


def fill_out_ids(df, filling_function, sort=False, sort_col='sort_col',
                 group_by='group_col', to_fill=['id1', 'id2']):

    df = df.copy()
    df.set_index(group_by, inplace=True)
    if sort:
        df.sort_values(by=sort_col, inplace=True)
    g = df.groupby(df.index, sort=False, group_keys=False)
    df = g.apply(filling_function, to_fill)
    df.reset_index(inplace=True)
    return df


def _fill_ids_concat(df, to_fill):
    df[to_fill] = df[to_fill].fillna(method='ffill')
    df[to_fill] = df[to_fill].fillna(method='bfill')
    return pd.concat([df])


def _fill_ids_plain(df, to_fill):
    df[to_fill] = df[to_fill].fillna(method='ffill')
    df[to_fill] = df[to_fill].fillna(method='bfill')
    return df


def test_fill_out_ids():
    input_df = pd.DataFrame(
        [
            ['a',       None,       1.0,    1],
            ['a',       None,       1.0,    3],
            ['a',       'name1',    np.nan, 2],

            ['b',       None,       2.0,    3],
            ['b',       'name1',    np.nan, 2],
            ['b',       'name2',    np.nan, 1],
        ],
        columns=['group_col', 'id1', 'id2', 'sort_col']
    )

    # this works
    fill_out_ids(input_df, _fill_ids_plain, sort=False)

    # this raises: ValueError: cannot reindex from a duplicate axis
    fill_out_ids(input_df, _fill_ids_plain, sort=True)

    # this works
    fill_out_ids(input_df, _fill_ids_concat, sort=True)

    # this works
    fill_out_ids(input_df, _fill_ids_concat, sort=False)


if __name__ == "__main__":
    test_fill_out_ids()

0 个答案:

没有答案