Rory
Rory

Reputation: 383

How to restore values between other values in Pandas

I have dataframe:

 import pandas as pd
    data = {'col1':[[0,1,2,3,4,5],[0,1,2,3,4,5,6,7,8,9],[0,1,2,3]],
           'col_2':[[2,4,5],[6,7,9],[0,1,2]]}
    
    df = pd.DataFrame(data)
            col1                           col_2
    0   [0, 1, 2, 3, 4, 5]              [2, 4, 5]
    1   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  [6, 7, 9]
    2   [0, 1, 2, 3]                    [0, 1, 2]

I would like to restore the values between the elements for the column col_2 from col_1 and get results in col_3

            col1                      col_2        col_3
0   [0, 1, 2, 3, 4, 5]              [2, 4, 5]   [2, 3, 4, 5]
1   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  [6, 7, 9]   [6, 7, 8, 9]
2   [0, 1, 2, 3]                    [0, 1, 2]    [0, 1, 2]

Upvotes: 0

Views: 21

Answers (1)

falafelocelot
falafelocelot

Reputation: 588

I think this should work:

df['col_3'] = df.apply(lambda row: [i for i in row['col_1'] if i >= min(row['col_2']) and i <= max(row['col_2'])], axis=1)

Upvotes: 1

Related Questions