Search code examples
pythonpandaslambdamethod-chaining

Drop pandas columns based on lambda during method chaining


I want to drop columns of a pandas DataFrame using a lambda. Questions like How can I use lambda to drop column of pandas dataframe? discuss this, but I want to be able to do it within a method chaining construct (which is not a condition in the other question). How can I do this?

Other questions, e.g. Method chaining solution to drop column level in pandas DataFrame, discuss column levels, but that is also different.


Solution

  • You can filter within in method chaining with pipe:

    import pandas as pd
    
    df = pd.DataFrame({'a': range(10), 'b': ["A"]*5 + ["B"]*5})
    df.some_chain_of_methods.pipe(lambda x: x.loc[x.b == "A"])