Home > Software design >  Why is lambda not working property 'value'?
Why is lambda not working property 'value'?

Time:05-07

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'

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

CodePudding user response:

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
  • Related