Search code examples
pythonpandas

Extracting specific columns to new DataFrame as a copy based on certain conditional values


This is a snippet of a dataframe I am working with, including angles for specific joints and their values.

mydf = pd.DataFrame({'LHip' : [4,5,6,6,7], 'LKnee' : [10,20,8,8], 'RHip' : [100,50,20,80], 'RKnee' : [-30,-50,-60,-70]})

My actual dataframe holds 54 variables with 27 joint angles, but each having a value for Left (L) and Right (R).

I would like to split this dataframe into 2 new dataframes, 1 holding all values for the Left side and 1 holding all values for the Right side.

From this question: Extracting specific selected columns to new DataFrame as a copy

I know that I can use

new = old[['A', 'C', 'D']].copy()

To make the copy dataframe, but I would like to build in the conditional value that 'L' and 'R' columns are selected automatically.

Any help on how to approach this would be vermy much appreciated.


Solution

  • You can use pandas.DataFrame.filter with a regex pattern:

    df_L = mydf.filter(regex="^L")
    df_R = mydf.filter(regex="^R")
    
       LHip  LKnee
    0     4     10
    1     5     20
    2     6      8
    3     6      8
       RHip  RKnee
    0   100    -30
    1    50    -50
    2    20    -60
    3    80    -70