Home > Software design >  How using isin inside lambda
How using isin inside lambda

Time:07-07

import pandas as pd
import numpy as np
    
Open_Time_s=['2022-04-30 11:05:00 03:00','2022-04-30 11:10:00 03:00', np.nan, np.nan]
intersect=[np.nan,np.nan,'intersect_2022-04-30 11:05:00 03:00','intersect_2022-04-30 11:10:00 03:00']
    
df = pd.DataFrame.from_dict({'Open Time':Open_Time_s,'intersect':intersect})
df['LEVEL']=np.nan

looking for matches on all lines 'Open Time' values intersect. You need to write the index values to the column 'LEVEL'

Using code : df['LEVEL']=df['intersect'].loc[df['intersect'].isna()==0].apply(lambda x: df[df['Open Time'].isin(x.replace(r'intersect_', ''))].index)

return error : only list-like objects are allowed to be passed to isin(), you passed a [str]. What is the possible alternative .isin ?

please tell me how to write similar code using lambda function:df[df['Open Time'].isin(df['intersect'].str.replace(r'intersect_', ''))].index.tolist()

need result :

         Open Time                        intersect                LEVEL
0  2022-04-30 11:05:00 03:00                                  NaN    NaN
1  2022-04-30 11:10:00 03:00                                  NaN    NaN
2                       None  intersect_2022-04-30 11:05:00 03:00    0
3                       None  intersect_2022-04-30 11:10:00 03:00    1

CodePudding user response:

Given:

Open_Time_s=['2022-04-30 11:05:00 03:00','2022-04-30 11:10:00 03:00', np.nan, np.nan]
intersect=[np.nan,np.nan,'intersect_2022-04-30 11:05:00 03:00','intersect_2022-04-30 11:10:00 03:00']    
df = pd.DataFrame.from_dict({'Open Time':Open_Time_s,'intersect':intersect})

Doing:

df[['intersect', 'intersect_time']] = df['intersect'].str.split('_', expand=True)

df['LEVEL'] = df.apply(lambda x: df[df['Open Time'].eq(x['intersect_time'])].index.tolist(), axis=1)

Output:

                   Open Time  intersect             intersect_time LEVEL
0  2022-04-30 11:05:00 03:00        NaN                        NaN    []
1  2022-04-30 11:10:00 03:00        NaN                        NaN    []
2                        NaN  intersect  2022-04-30 11:05:00 03:00   [0]
3                        NaN  intersect  2022-04-30 11:10:00 03:00   [1]
  • Related