简体   繁体   中英

How using isin inside lambda

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM