首页 > 解决方案 > 如何在 Pandas 中添加行切片?

问题描述

我有df一些数据的数据框。我也有一个切片selection条件cond_1

    def cond1(row):
        if some_condition_1:
            return True
        return False

    def cond2(row):
        if some_condition_2:
            return True
        return False

    selection = df[df.apply(cond1, axis=1)]

    # Some logic here
    #...
    #
    # Later:

但是我需要使用其他条件附加一些数据cond2 所以我可以扩展selection使用cond2还是应该selection2先加入然后加入它们?

标签: pythonpandas

解决方案


...
...

selection1 = dataframe based on some condition
selection2 = dataframe based on some condition

selection1 = selection1[selection1.apply(cond1, axis=1)]
selection2 = selection2[selection2.apply(cond2, axis=1)]

pd.concat([selection1, selection2])

推荐阅读