这个df2'CLINE_TYPE‘
Increase_FALSE
Decrease
Increase_FALSE
Increase_SUPERPOSITION
Decrease_FALSE
Increase
Increase_SUPERPOSITION
Decrease_FALSE
Increase
Increase_SUPERPOSITION这一职能:
def nearest(lst, target):
return min(lst, key=lambda x: abs(x-target))我需要从lamda获得一个值,我得到了一个错误:'AttributeError:'str‘对象没有属性值’value‘
所有代码:
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']])查找列表中最近的最小索引
发布于 2022-05-07 10:32:02
Series.apply将串联中的值传递给函数,因此通常它没有任何属性。由于您希望访问行索引,所以您需要的是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 7https://stackoverflow.com/questions/72151463
复制相似问题