by using .any function is this the correct approach

Issue

Dataframe with Number column:
Dataframe with Number column

list_1 = ['22','33','44']

df = {'number' : '22,33,0' , '33' , '22,0'}

any(item in df['number'] for item in list_1)

I want to check whether the any string in dataframe is in the list_1.

Solution

There is most likely a better or faster way to do this, but I believe this will give you the results you are expecting

list_1 = ['22','33','44']
df = pd.DataFrame({'number' : ['22,33,0', '33', '22,0', '45']})
df = df.reset_index()
df_index = df
df['number'] = df['number'].str.split(',')
df = df.explode('number')
df['Check'] = np.where(df['number'].isin(list_1), True, False)
df = df.mask(df['Check'] == False).dropna().groupby('index').agg('first').reset_index()
df = pd.merge(df_index, df, how = 'left', left_on = 'index', right_on = 'index', suffixes=('', '_y'))
df[['number', 'Check']].fillna(False)

Answered By – ArchAngelPwn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published