Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is lambda not working property 'value'?

this df2[‘CLINE_TYPE’]:

Increase_FALSE
Decrease
Increase_FALSE
Increase_SUPERPOSITION
Decrease_FALSE
Increase
Increase_SUPERPOSITION
Decrease_FALSE
Increase
Increase_SUPERPOSITION

this function :

def nearest(lst, target):
  return min(lst, key=lambda x: abs(x-target))

I need to get a value from lamda, I get an error: ‘AttributeError: ‘str’ object has no attribute ‘values’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

all code :

import pandas as pd
import numpy as np
import re

def nearest(lst, target):
  return min(lst, key=lambda x: abs(x-target))

    df2['res']=np.nan
    
    df2['res'] = df2['CLINE_TYPE'].apply(lambda x: nearest(df2.loc[df2['CLINE_TYPE'].str.contains('Increase')].index.to_list(), x.name)
                                        if bool(re.match(r'Decrease', x.values))==True else
                                        nearest(df2.loc[df2['CLINE_TYPE'].str.contains('Decrease')].index.to_list(), x.name))
    
    print(df2[['CLINE_TYPE','res']])

looking for the nearest smallest index of a list

>Solution :

Series.apply pass value in Series to function, so normally it doesn’t have any attribute. Since you want to access row index, what you want is DataFrame.apply:

df2['res'] = df2.apply(lambda row: nearest(df2.loc[df2['CLINE_TYPE'].str.contains('Increase')].index.to_list(), row.name)
                       if bool(re.match(r'Decrease', row['CLINE_TYPE']))==True else
                       nearest(df2.loc[df2['CLINE_TYPE'].str.contains('Decrease')].index.to_list(), row.name), axis=1)
print(df2[['CLINE_TYPE','res']])

               CLINE_TYPE  res
0          Increase_FALSE    1
1                Decrease    0
2          Increase_FALSE    1
3  Increase_SUPERPOSITION    4
4          Decrease_FALSE    3
5                Increase    4
6  Increase_SUPERPOSITION    7
7          Decrease_FALSE    6
8                Increase    7
9  Increase_SUPERPOSITION    7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading